1、首先我们要在Manifest.xml文件中配置一个<receiver/>标签,这个标签必须有一个android:name属性,值为继承自BroadcastReceiver类的接收器类,并复写onReceiver方法,在该方法中处理接收到广播后需要处理的事情!
2、<receiver/>标签还有一个子标签为<intent-filter/>,这个标签很重要,是指定接收器需要接收哪种广播
添加的监听器配置文件内容
MyBroadCast是继承了BroadcastReceiver的类
<receiver android:name="MyBroadCast"> <intent-filter> <action android:name="hb.com.BroadCastDemo.MYBROADCAST"/> </intent-filter> </receiver>
给按钮添加绑定的事件,发送广播的过程
btn.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { System.out.println("onClick"); Intent intent = new Intent(); intent.setAction(MYBROADCAST); sendBroadcast(intent); } });
接收广播处理的过程
public class MyBroadCast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { System.out.println("onReceive"); } }
备注:在AndroidManifest.xml文件中注册,无论应用程序是否处于开启或关闭状态,它任然会是监听状态,这种方式不是很合理
在应用程序的代码中进行注册,registerReceiver()和unregisterReceiver()两个方法
Notification和NotificationManager的使用
通过他们可以显示广播信息的内容、图标以及振动等信息
显示效果:类似于收到短信的提示信息
public class BroadCastDemo extends Activity { Notification nf; NotificationManager nm; private static final String MYBROADCAST = "hb.com.BroadCastDemo.MYBROADCAST"; private static final int MYID = 1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //得到NotificationManager对象 String service = this.NOTIFICATION_SERVICE; nm = (NotificationManager)this.getSystemService(service); //实例化Notification nf = new Notification(); nf.icon = R.drawable.icon; nf.tickerText = "notification test"; nf.when = System.currentTimeMillis(); findViewById(R.id.broadCastBtn).setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(); //发送自定义的广播类型 intent.setAction(MYBROADCAST); PendingIntent pi = PendingIntent.getBroadcast(BroadCastDemo.this, 0, intent, 0); nf.setLatestEventInfo(BroadCastDemo.this, "my title", "my content", pi); nm.notify(MYID, nf); } }); findViewById(R.id.cancelCastBtn).setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { //取消广播 nm.cancel(MYID); } }); } }
AlarmManager的使用
AlarmManager提供了一种系统级的提示服务,允许你安排在将来的某个时间执行一个服务
findViewById(R.id.alarmManagerOpen).setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(MYBROADCAST); PendingIntent pi = PendingIntent.getBroadcast(BroadCastDemo.this, 0, intent, 0); long time = System.currentTimeMillis(); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.RTC_WAKEUP, time, 8 * 1000, pi); } });