`

玩转Android---组件篇---Broadcast Receiver(广播接收器)

阅读更多

Braodcast Receiver顾名思义就是广播接收器,它和时间处理机制类似,但是事件处理机制是程序组件级别的(比如:按钮的单击事件),而广播事件处理机制是系统级别的。我们可以用Intent来启动一个组件,也可以用sendBroadcast()方法发起一个系统级别的事件广播来传递消息。我们同样可以在自己的应用程序中实现Broadcast Receiver来监听和响应广播的Intent。

事件的广播通过创建Intent对象并调用sendBroadcast()方法将广播发出。事件的接受是通过定义一个继承BroadcastReceiver的类来实现的,继承该类后覆盖其onReceive()方法,在该方法中响应时间。

下面是android系统中定义了很多标准的Broadcast Action来响应系统的广播事件。

①ACTION_TIME_CHANGED(时间改变时触发)

②ACTION_BOOT_COMPLETED(系统启动完成后触发)--比如有些程序开机后启动就是用这种方式来实现的

③ACTION_PACKAGE_ADDED(添加包时触发)

④ACTION_BATTERY_CHANGED(电量低时触发)

详细:标准广播ACTION常量

常量名称

常量值

意义

ACTION_BOOT_COMPLETED

android.intent.action.BOOT_COMPLETED

系统启动完成

ACTION_TIME_CHANGED

android.intent.action.ACTION_TIME_CHANGED

时间改变

ACITON_DATE_CHANGED

android.intent.action.ACTION_DATE_CHANGED

日期改变

ACTION_TIMEZONE_CHANGED

android.intent.action.ACTION_TIMEZONE_CHANGED

时区该表

ACTION_BATTERY_LOW

android.intent.action.ACTION_BATTERY_LOW

电量低

ACTION_MEDIA_EJECT

android.intent.action.ACTION_MEDIA_EJECT

插入或拔出外部媒体

ACTION_MEDIA_BUTTON

android.intent.action.ACTION_MEDIA_BUTTON

按下媒体按钮

ACTION_PACKAGE_ADDED

android.intent.action.ACTION_PACKAGE_ADDED

添加包

ACTION_PACKAGE_REMOVED

android.intent.action.ACTION_PACKAGE_REMOVED

删除包

 

在这里,要练习3个内容

①自定义Broadcast Receiver

②Notification和NotificationManager的使用

③AlarmManager的使用

 

1、首先看一个自定义的广播事件的例子

package org.hualang.broadcast;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BroadCastTest extends Activity {
    /** Called when the activity is first created. */
	private static final String MY_ACTION="org.hualang.broadcast.action.MY_ACTION";
	private Button btn;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn=(Button)findViewById(R.id.button);
        btn.setOnClickListener(new OnClickListener()
        {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent=new Intent();
				intent.setAction(MY_ACTION);
				intent.putExtra("msg", "同志们好!同志们辛苦啦!");
				sendBroadcast(intent);
			}
        	
        });
    }
}

 

MyReceiver.java

package org.hualang.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		String msg=arg1.getStringExtra("msg");
		Toast.makeText(arg0, msg, Toast.LENGTH_LONG).show();
	}
	
}

 

注意:在AndroidManifest.xml文件中注册

<receiver android:name="MyReceiver">
			<intent-filter>
				<action android:name="org.hualang.broadcast.action.MY_ACTION"/>
			</intent-filter>
		</receiver>

 

 

我们还可以在AndroidManifest.xml文件中注销一个广播接收器,一般在Activity.onResume()方法中使用Context.registerReceiver()方法来注册一个广播接收器,在Activity.onPause()中使用unregisterReceiver(r)方法注销一个广播接收器,例如:

//实例化intent过滤器

IntentFilter filter = new IntentFilte();

//实例化Receiver

MyReceiver r = new Receiver();

//注册Receiver

registerReceiver(r,filter);

 

为了注销一个BroadcastReceiver,应使用Context.unregisterReceiver方法,传入一个BroadcastReceiver实例

//注销

unregisterReceiver(r);

 

2、下面的是Notification的例子,比如手机来短信的时候,会在屏幕最上边有一个通知,那个就是Notification

DisplayActivity.java

package org.hualang.notify;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class DisplayActivity extends Activity {
	private Button cancelbtn;
	private Notification n;
	private NotificationManager nm;
	private static final int ID=1;
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main2);
		cancelbtn = (Button)findViewById(R.id.button2);
		String service = NOTIFICATION_SERVICE;
		nm = (NotificationManager)getSystemService(service);
		
		n = new Notification();
		int icon = n.icon =R.drawable.icon;
		String tickerText = "喜欢HTC的样子,喜欢defy的配置";
		long when = System.currentTimeMillis();
		n.icon = icon;
		n.tickerText = tickerText;
		n.when = when;
		
		Intent intent = new Intent(this,NotifyTest2.class);
		PendingIntent pi = PendingIntent.getActivity(this, 0 , intent , 0);
		n.setLatestEventInfo(this, "My Title", "My Content", pi);
		nm.notify(ID, n);
		cancelbtn.setOnClickListener(cancelListener);
	}
	private OnClickListener cancelListener=new OnClickListener()
	{
		public void onClick(View v)
		{
			nm.cancel(ID);
		}
	};
}

 MyReceiver.java

package org.hualang.notify;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		Intent i=new Intent();
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.setClass(context,DisplayActivity.class);
		context.startActivity(i);
	}
	
}

 

NotifyTest2.java

package org.hualang.notify;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NotifyTest2 extends Activity {
    /** Called when the activity is first created. */
	private Button btn;
	private static final String MY_ACTION="org.hualang.notify.aciton.MY_ACITON";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn=(Button)findViewById(R.id.button);
        btn.setOnClickListener(listener);
    }
    private OnClickListener listener=new OnClickListener()
    {
    	public void onClick(View v)
    	{
    		Intent intent=new Intent();
    		intent.setAction(MY_ACTION);
    		sendBroadcast(intent);
    	}
    };
}

 

注册AndroidManifest.xml

<receiver android:name="MyReceiver">
			<intent-filter>
				<action android:name="org.hualang.notify.aciton.MY_ACITON"/>
			</intent-filter>
		</receiver>
		<activity android:name="DisplayActivity">
		</activity>

 

运行结果如下:




 

3、下面是AlarmManager的例子,它是一个闹钟,感兴趣的朋友可以自己写一个小闹钟

AlarmManager常用的属性和方法

属性或方法名称

说明

ELAPSED_REALTIME

设置闹钟时间,从系统启动开始

ELAPSED_REALTIME_WAKEUP

设置闹钟时间,从系统启动开始,如火设备休眠则唤醒

INTERVAL_DAY

设置闹钟时间,间隔一天

INTERVAL_FIFTEEN_MINUTES

间隔15分钟

INTERVAL_HALF_DAY

间隔半天

INTERVAL_HALF_HOUR

间隔半小时

INTERVAL_HOUR

间隔1小时

RTC

设置闹钟时间,从系统当前时间开始(System.currentTimeMillis())

RTC_WAKEUP

设置闹钟时间,从系统当前时间开始,设备休眠则唤醒

set(int type,long tiggerAtTime,PendingIntent operation)

设置在某个时间执行闹钟

setRepeating(int type,long triggerAtTiem,long interval,PendingIntent operation)

设置在某个时间重复执行闹钟

setInexactRepeating(int type,long triggerAtTiem,long interval,PendingIntent operation)

是指在某个时间重复执行闹钟,但不是间隔固定时间

 

AlarmTest.java

package org.hualang.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class AlarmTest extends Activity {
    /** Called when the activity is first created. */
	private Button btn1,btn2;
	private static final String BC_ACTION="org.hualang.alarm.action.BC_ACTION";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn1 = (Button)findViewById(R.id.button1);
        btn2 = (Button)findViewById(R.id.button2);
        
        final AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        Intent intent = new Intent();
        intent.setAction(BC_ACTION);
        intent.putExtra("msg", "你该起床了");
        final PendingIntent pi = PendingIntent.getBroadcast(AlarmTest.this, 0, intent, 0);
        final long time = System.currentTimeMillis();

        
        btn1.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View v)
        	{
        		
        		am.setRepeating(AlarmManager.RTC_WAKEUP, time, 5*1000, pi);
        	}
        });
        btn2.setOnClickListener(new OnClickListener()
        {
        	public void onClick(View v)
        	{
        		am.cancel(pi);
        	}
        });
    }
}

 

MyReceiver.java

package org.hualang.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String msg=intent.getStringExtra("msg");
		Log.v("SERVICE","QIAN----------------------");
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
		Log.v("SERVICE", "HOU-----------------------");
	}

}

 

注册AndroidManifest.xml

<receiver android:name="MyReceiver">
			<intent-filter>
				<action android:name="org.hualang.alarm.action.BC_ACTION"/>
			</intent-filter>
		</receiver>

 运行结果:


 

 点击设置闹钟后,会每隔5秒弹出一个Toast,点击取消闹钟就不会弹出了



 

  • 大小: 13.3 KB
  • 大小: 8.4 KB
  • 大小: 8.5 KB
  • 大小: 10.4 KB
  • 大小: 14.4 KB
分享到:
评论
1 楼 Butterfly_ 2013-08-13  
   op   s:  
   

相关推荐

Global site tag (gtag.js) - Google Analytics