BroadCast Receiver的使用
定义
广播接收器分为标准广播和有序广播,标准广播是异步执行的广播,有序广播是同步执行的,同一时刻只有一个广播接收器会收到广播,执行结束后,广播才会继续传递。
静态注册
在Androidmanifest.xml中添加<receiver>节点,并在代码中定义相应的类。在receiver字段里面可以指定priority来指定receiver的优先级,优先级高的会先接收到消息。如果不指定,后注册的receiver先接收到消息
<receiver android:name=".BootCompleteReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> public class BootCompleteReceiver extends BroadcastReceiver { //static registered in AndroidManifest.xml @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, "Boot Complete", Toast.LENGTH_SHORT).show(); } }
动态注册
可以在代码中注册,这种方法比较灵活,可以自由的注册与注销,但是缺点是必须要程序启动才能收到广播。只需要创建一个BroadcastReceiver的子类并重写父类的onReceive函数就可以了。当有广播到来时,onReceive方法就会被执行。
public class MyReceiver extends BroadcastReceiver { public static final String ACTION = "com.wanxiang.www.learnbroadcastreceiver.intent.action.myReceiver";
case R.id.btnRegister: if (myReceiver == null){ myReceiver = new MyReceiver(); registerReceiver(myReceiver, new IntentFilter(MyReceiver.ACTION)); } break; case R.id.btnUnRegister: if (myReceiver != null){ unregisterReceiver(myReceiver); myReceiver =null; } break;
自定义广播
其他都同动态静态注册的broadcastreceiver一样,只是intent-filter写的是自己定义的broadcast,同样在类中也要写发送相应的broadcast(可能在一个button的click中):
Intent intent = new Intent("com.wanxiang.www.broadcastreceiver.MY_BROADCAST"); //标准广播 sendBroadcast(intent); //有序广播,可以被abortBroadcast()截断 sendOrderedBroadcast(intent,null);
有序广播
发送的有序广播可以在BroadcastReceiver的onReceive函数中被截断:
sendOrderedBroadcast(intent, null);
@Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. System.out.println("MyReceiver1接受到了消息"); abortBroadcast(); }
本地广播
只让broadcast在应用程序内部进行传递