BroadcastReceiver
在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。而BroadcastReceiver是对发送出来的 Broadcast进行过滤接受并响应的一类组件。
下面将详细的阐述如何发送Broadcast和使用BroadcastReceiver过滤接收的过程:
首先在需要发送信息的地方,把要发送的信息和用于过滤的信息(如Action、Category)装入一个Intent对象,然后通过调用 sendOrderBroadcast()或sendStickyBroadcast()方法,把 Intent对象以广播方式发送出去。
当Intent发送以后,所有已经注册的BroadcastReceiver会检查注册时的IntentFilter是否与发送的Intent相匹配,若匹配则就会调用BroadcastReceiver的onReceive()方法。所以当我们定义一个BroadcastReceiver的时候,都需要实现onReceive()方法。
注册BroadcastReceiver有两种方式:
静态注册:在AndroidManifest.xml中用标签生命注册,并在标签内用标签设置过滤器。
1 <receiver android:name="myRecevice"> //继承BroadcastReceiver,重写onReceiver方法 2 <intent-filter> 3 <action android:name="com.dragon.net"></action> //使用过滤器,接收指定action广播 4 </intent-filter> 5 </receiver>
动态注册:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(String); //为BroadcastReceiver指定action,使之用于接收同action的广播
registerReceiver(BroadcastReceiver,intentFilter);
一般:在onStart中注册,onStop中取消unregisterReceiver
指定广播目标Action:Intent intent = new Intent(actionString);
并且可通过Intent携带消息 :intent.putExtra("msg", "hi,我通过广播发送消息了");
发送广播消息:Context.sendBroadcast(intent )
其中在动态注册中可将BroadcastReceiver的继承类进行封装,添加构造函数和BroadcastReceiver注册
1 import android.app.Notification; 2 import android.app.NotificationManager; 3 import android.app.PendingIntent; 4 import android.content.BroadcastReceiver; 5 import android.content.Context; 6 import android.content.Intent; 7 import android.content.IntentFilter; 8 9 public class BroadcastReceiverHelper extends BroadcastReceiver { 10 11 NotificationManager mn=null; 12 Notification notification=null; 13 Context ct=null; 14 BroadcastReceiverHelper receiver; 15 16 public BroadcastReceiverHelper(Context c){ 17 ct=c; 18 receiver=this; 19 } 20 21 //注册 22 public void registerAction(String action){ 23 IntentFilter filter=new IntentFilter(); 24 filter.addAction(action); 25 ct.registerReceiver(receiver, filter); 26 } 27 28 @Override 29 public void onReceive(Context context, Intent intent) { 30 // TODO Auto-generated method stub 31 String msg=intent.getStringExtra("msg"); 32 int id=intent.getIntExtra("who", 0); 33 if(intent.getAction().equals("com.cbin.sendMsg")){ 34 mn=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 35 notification=new Notification(R.drawable.icon, id+"发送广播", System.currentTimeMillis()); 36 Intent it = new Intent(context,Main.class); 37 PendingIntent contentIntent=PendingIntent.getActivity(context, 38 0, it, 0); 39 notification.setLatestEventInfo(context, 40 "msg", msg, contentIntent); 41 mn.notify(0, notification); 42 } 43 } 44 }
然后再Activity中声明BroadcastReceiver的扩展对象,在onStart中注册,onStop中卸载
BroadcastReceiverHelper rhelper; @Override public void onStart(){ //注册广播接收器 rhelper=new BroadcastReceiverHelper(this); rhelper.registerAction("com.cbin.sendMsg"); super.onStart(); } @Override public void onStop(){ //取消广播接收器 unregisterReceiver(rhelper); super.onStop(); }