详解Android中BroadCastReceiver组件

2019-12-10 18:57:11王旭

代码改完之后,我们需要为三个接收者注册广播地址,我们修改一下AndroidMainfest.xml文件:

<receiver android:name=".FirstReceiver"> 
  <intent-filter android:priority="1000"> 
    <action android:name="android.intent.action.MY_BROADCAST"/> 
    <category android:name="android.intent.category.DEFAULT" /> 
  </intent-filter> 
</receiver> 
<receiver android:name=".SecondReceiver"> 
  <intent-filter android:priority="999"> 
    <action android:name="android.intent.action.MY_BROADCAST"/> 
    <category android:name="android.intent.category.DEFAULT" /> 
  </intent-filter> 
</receiver> 
<receiver android:name=".ThirdReceiver"> 
  <intent-filter android:priority="998"> 
    <action android:name="android.intent.action.MY_BROADCAST"/> 
    <category android:name="android.intent.category.DEFAULT" /> 
  </intent-filter> 
</receiver> 

我们看到,现在这三个接收者的多了一个android:priority属性,并且依次减小。这个属性的范围在-1000到1000,数值越大,优先级越高。 
现在,我们需要修改一下发送广播的代码,如下:

public void send(View view) { 
  Intent intent = new Intent("android.intent.action.MY_BROADCAST"); 
  intent.putExtra("msg", "hello receiver."); 
  sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION"); 
} 

注意,使用sendOrderedBroadcast方法发送有序广播时,需要一个权限参数,如果为null则表示不要求接收者声明指定的权限,如果不为null,则表示接收者若要接收此广播,需声明指定权限。这样做是从安全角度考虑的,例如系统的短信就是有序广播的形式,一个应用可能是具有拦截垃圾短信的功能,当短信到来时它可以先接受到短信广播,必要时终止广播传递,这样的软件就必须声明接收短信的权限。