Android的普通广播和有序广播

普通广播:

普通广播对于任何广播的接收者来说,都是异步的,每个接收者都无需等待即可接收到广播,相互之间没有影响。这种广播无法终止,即无法阻止其他广播接收者的接收动作。

发送普通广播:

  1. Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  2. intent.putExtra("msg""Hello receiver.");  
  3. sendBroadcast(intent);
详见我的另一篇博客: Android BroadcastReceiver的简单使用 。


有序广播:

有序广播会将广播优先发送给接收优先级较高的BroadcastReceiver,然后优先级高的BroadcastReceiver再传给优先级低的BroadcastReceiver,前者可以终止广播的继续传播。在优先级高的BroadcastReceiver中,还可以通过setResultExtras()方法,将一个Bundle对象设置为结果集对象,传递到下一个BroadcastReceiver那里。而低优先级的BroadcastReceiver可以通过getResultExtras()方法获取到最新的经过处理的信息集合。

优先级的设置:

通常是在AndroidManifest.xml中注册广播地址时,通过android:priority属性设置广播接收的优先级。该属性值的范围是-1000~1000,数值越大,优先级越高。如:

  1. <receiver android:name=".MyBroadcastReceiver">  
  2.     <intent-filter android:priority="1000">  
  3.           <action android:name="android.intent.action.MY_BROADCAST" />  
  4.           <category android:name="android.intent.category.DEFAULT" />  
  5.     intent-filter>  
  6. receiver>

发送有序广播:

  1. Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  2. intent.putExtra("msg""Hello receiver.");  
  3. sendOrderedBroadcast(intent, "bigben.permission.MY_BROADCAST_PERMISSION"); 
发送有序广播的第二个参数是一个权限参数,如果为null则表示不要求BroadcastReceiver声明指定的权限。如果不为null,则表示接收者若想要接收此广播,需要声明指定的权限(为了安全)。以上发送有序广播的代码需要在AndroidManifest.xml中自定义一个权限:
  1. <permission android:protectionLevel="normal"  
  2.         android:name="bigben.permission.MY_BROADCAST_PERMISSION" /> 
然后声明使用了此权限:
  1. <uses-permission android:name="bigben.permission.MY_BROADCAST_PERMISSION" />  

终止广播:

在优先级高的BroadcastReceiver的onReceiver()方法中添加代码:

  1. abortBroadcast();  
则广播将不会再继续往下传播,即在低优先级的BroadcastReceiver中将不会在接收到广播消息。

你可能感兴趣的:(Android)