BroadcastReceiver详解

2018/4/21

在Android系统中,广播体现在方方面面,例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能;当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作;当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户及时保存进度,等等。

Android中的广播机制设计的非常出色,很多事情原本需要开发者亲自操作的,现在只需等待广播告知自己就可以了,大大减少了开发的工作量和开发周期。而作为应用开发者,就需要数练掌握Android系统提供的一个开发利器,那就是BroadcastReceiver。下面我们就对BroadcastReceiver逐一地分析和演练,了解和掌握它的各种功能和用法。

首先,我们来演示一下创建一个BroadcastReceiver,并让这个BroadcastReceiver能够根据我们的需要来运行。

要创建自己的BroadcastReceiver对象,我们需要继承android.content.BroadcastReceiver,并实现其onReceive方法。下面我们就创建一个名为MyReceiver广播接收者:

 

[java] view plain copy
  1. package com.scott.receiver;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7.   
  8. public class MyReceiver extends BroadcastReceiver {  
  9.       
  10.     private static final String TAG = "MyReceiver";  
  11.       
  12.     @Override  
  13.     public void onReceive(Context context, Intent intent) {  
  14.         String msg = intent.getStringExtra("msg");  
  15.         Log.i(TAG, msg);  
  16.     }  
  17.   
  18. }  

在onReceive方法内,我们可以获取随广播而来的Intent中的数据,这非常重要,就像无线电一样,包含很多有用的信息。

在创建完我们的BroadcastReceiver之后,还不能够使它进入工作状态,我们需要为它注册一个指定的广播地址。没有注册广播地址的BroadcastReceiver就像一个缺少选台按钮的收音机,虽然功能俱备,但也无法收到电台的信号。下面我们就来介绍一下如何为BroadcastReceiver注册广播地址。

静态注册

静态注册是在AndroidManifest.xml文件中配置的,我们就来为MyReceiver注册一个广播地址:

 

[html] view plain copy
  1. <receiver android:name=".MyReceiver">  
  2.             <intent-filter>  
  3.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  4.                 <category android:name="android.intent.category.DEFAULT" />  
  5.             </intent-filter>  
  6.         </receiver>  

配置了以上信息之后,只要是android.intent.action.MY_BROADCAST这个地址的广播,MyReceiver都能够接收的到。注意,这种方式的注册是常驻型的,也就是说当应用关闭后,如果有广播信息传来,MyReceiver也会被系统调用而自动运行。

动态注册

动态注册需要在代码中动态的指定广播地址并注册,通常我们是在Activity或Service注册一个广播,下面我们就来看一下注册的代码:

 

[java] view plain copy
  1. MyReceiver receiver = new MyReceiver();  
  2.           
  3. IntentFilter filter = new IntentFilter();  
  4. filter.addAction("android.intent.action.MY_BROADCAST");  
  5.           
  6. registerReceiver(receiver, filter);  

注意,registerReceiver是android.content.ContextWrapper类中的方法,Activity和Service都继承了ContextWrapper,所以可以直接调用。在实际应用中,我们在Activity或Service中注册了一个BroadcastReceiver,当这个Activity或Service被销毁时如果没有解除注册,系统会报一个异常,提示我们是否忘记解除注册了。所以,记得在特定的地方执行解除注册操作:

 

 

[java] view plain copy
  1. @Override  
  2. protected void onDestroy() {  
  3.     super.onDestroy();  
  4.     unregisterReceiver(receiver);  
  5. }  

 

执行这样行代码就可以解决问题了。注意,这种注册方式与静态注册相反,不是常驻型的,也就是说广播会跟随程序的生命周期。

我们可以根据以上任意一种方法完成注册,当注册完成之后,这个接收者就可以正常工作了。我们可以用以下方式向其发送一条广播:

 

[java] view plain copy
  1. public void send(View view) {  
  2.     Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  3.     intent.putExtra("msg""hello receiver.");  
  4.     sendBroadcast(intent);  
  5. }  

 

注意,sendBroadcast也是android.content.ContextWrapper类中的方法,它可以将一个指定地址和参数信息的Intent对象以广播的形式发送出去。

点击发送按钮,执行send方法,控制台打印如下:

看到这样的打印信息,表明我们的广播已经发出去了,并且被MyReceiver准确无误的接收到了。

上面的例子只是一个接收者来接收广播,如果有多个接收者都注册了相同的广播地址,又会是什么情况呢,能同时接收到同一条广播吗,相互之间会不会有干扰呢?这就涉及到普通广播和有序广播的概念了。

普通广播(Normal Broadcast)

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

为了验证以上论断,我们新建三个BroadcastReceiver,演示一下这个过程,FirstReceiver、SecondReceiver和ThirdReceiver的代码如下:

 

[java] view plain copy
  1. package com.scott.receiver;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.util.Log;  
  7.   
  8. public class FirstReceiver extends BroadcastReceiver {  
  9.       
  10.     private static final String TAG = "NormalBroadcast";  
  11.       
  12.     @Override  
  13.     public void onReceive(Context context, Intent intent) {  
  14.         String msg = intent.getStringExtra("msg");  
  15.         Log.i(TAG, "FirstReceiver: " + msg);  
  16.     }  
  17.   
  18. }  
[java] view plain copy
  1. public class SecondReceiver extends BroadcastReceiver {  
  2.       
  3.     private static final String TAG = "NormalBroadcast";  
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         String msg = intent.getStringExtra("msg");  
  8.         Log.i(TAG, "SecondReceiver: " + msg);  
  9.     }  
  10.   
  11. }  
[java] view plain copy
  1. public class ThirdReceiver extends BroadcastReceiver {  
  2.       
  3.     private static final String TAG = "NormalBroadcast";  
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         String msg = intent.getStringExtra("msg");  
  8.         Log.i(TAG, "ThirdReceiver: " + msg);  
  9.     }  
  10.   
  11. }  

然后再次点击发送按钮,发送一条广播,控制台打印如下:

 

看来这三个接收者都接收到这条广播了,我们稍微修改一下三个接收者,在onReceive方法的最后一行添加以下代码,试图终止广播:

 

[java] view plain copy
  1. abortBroadcast();  

再次点击发送按钮,我们会发现,控制台中三个接收者仍然都打印了自己的日志,表明接收者并不能终止广播。

 

有序广播(Ordered Broadcast)

有序广播比较特殊,它每次只发送到优先级较高的接收者那里,然后由优先级高的接受者再传播到优先级低的接收者那里,优先级高的接收者有能力终止这个广播。

为了演示有序广播的流程,我们修改一下上面三个接收者的代码,如下:

 

[java] view plain copy
  1. package com.scott.receiver;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8.   
  9. public class FirstReceiver extends BroadcastReceiver {  
  10.       
  11.     private static final String TAG = "OrderedBroadcast";  
  12.       
  13.     @Override  
  14.     public void onReceive(Context context, Intent intent) {  
  15.         String msg = intent.getStringExtra("msg");  
  16.         Log.i(TAG, "FirstReceiver: " + msg);  
  17.           
  18.         Bundle bundle = new Bundle();  
  19.         bundle.putString("msg", msg + "@FirstReceiver");  
  20.         setResultExtras(bundle);  
  21.     }  
  22.   
  23. }  
[java] view plain copy
  1. public class SecondReceiver extends BroadcastReceiver {  
  2.       
  3.     private static final String TAG = "OrderedBroadcast";  
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         String msg = getResultExtras(true).getString("msg");  
  8.         Log.i(TAG, "SecondReceiver: " + msg);  
  9.           
  10.         Bundle bundle = new Bundle();  
  11.         bundle.putString("msg", msg + "@SecondReceiver");  
  12.         setResultExtras(bundle);  
  13.     }  
  14.   
  15. }  
[java] view plain copy
  1. public class ThirdReceiver extends BroadcastReceiver {  
  2.       
  3.     private static final String TAG = "OrderedBroadcast";  
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         String msg = getResultExtras(true).getString("msg");  
  8.         Log.i(TAG, "ThirdReceiver: " + msg);  
  9.     }  
  10.   
  11. }  

我们注意到,在FirstReceiver和SecondReceiver中最后都使用了setResultExtras方法将一个Bundle对象设置为结果集对象,传递到下一个接收者那里,这样以来,优先级低的接收者可以用getResultExtras获取到最新的经过处理的信息集合。

 

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

 

[html] view plain copy
  1. <receiver android:name=".FirstReceiver">  
  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>  
  7. <receiver android:name=".SecondReceiver">  
  8.     <intent-filter android:priority="999">  
  9.         <action android:name="android.intent.action.MY_BROADCAST"/>  
  10.         <category android:name="android.intent.category.DEFAULT" />  
  11.     </intent-filter>  
  12. </receiver>  
  13. <receiver android:name=".ThirdReceiver">  
  14.     <intent-filter android:priority="998">  
  15.         <action android:name="android.intent.action.MY_BROADCAST"/>  
  16.         <category android:name="android.intent.category.DEFAULT" />  
  17.     </intent-filter>  
  18. </receiver>  

我们看到,现在这三个接收者的<intent-filter>多了一个android:priority属性,并且依次减小。这个属性的范围在-1000到1000,数值越大,优先级越高。

 

现在,我们需要修改一下发送广播的代码,如下:

 

[java] view plain copy
  1. public void send(View view) {  
  2.     Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  3.     intent.putExtra("msg""hello receiver.");  
  4.     sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");  
  5. }  

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

 

所以我们在AndroidMainfest.xml中定义一个权限: