标签:
1.静态注册。
在manifest中注册。
1 <receiver android:name="com.exce.learnbroadcastreceiver.MyReceiver"></receiver>
然后在activity中使用sendBroadcast(Intent)方法。其中参数是Intent.
1 Intent intent=new Intent(this,MyReceiver.class); 2 intent.putExtra("data", "exer"); //携带数据 3 sendBroadcast(intent);
2.动态注册。
不需要在manifest中注册。
在代码中使用registerReceiver()和unregisterReceiver()进行广播的注册和取消注册。
registerReceiver(BroadcastReceiver receiver, IntentFilter filter),第一个参数是receiver,第二个参数是intentfilter。
unregisterReceiver(BroadcastReceiver receiver),参数是receiver。
代码:
1 private MyReceiver receiver;
...
1 case R.id.regBroadCast: 2 if (receiver==null) { 3 receiver=new MyReceiver(); 4 registerReceiver(receiver, new IntentFilter(MyReceiver.ACTION)); 5 } 6 break; 7 case R.id.unRegBroadCast: 8 if (receiver!=null) { 9 unregisterReceiver(receiver); 10 receiver=null; 11 }
MyReceiver:
1 public static final String ACTION="com.exec.learnbroadcastreceiver.intent.action";
通过常量ACTION,new IntentFilter(MyReceiver.ACTION)获得intentFilter。然后就可以注册广播。
动态注册的广播,一定要在销毁的时候进行取消注册。即registerReceiver()和unregisterReceiver()必须同时出现。
3.Broadcast的优先级
BroadcastReceiver的优先级可以通过manifest中的intent-filter的android:priority=""属性。android:priority="9"需要填写一个数字,数字越大,优先级越高。
实现有序广播,可以使用sendOrderedBroadcast(Intent intent, String receiverPermission)方法,然后配合android:priority=""属性,进行有序广播
同时想要截断广播的话,在继承BroadcastReceiver的MyReceiver的onReceive()方法中使用abortBroadcast()方法,就可以截断广播。
Android开发之BroadcastReceiver的使用
标签:
原文地址:http://www.cnblogs.com/liyiran/p/4639489.html