zoukankan      html  css  js  c++  java
  • BroadcastReceiver详解(一)

    今天我们来讲一下Android中BroadcastReceiver的相关知识。

    BroadcastReceiver也就是“广播接收者”的意思,顾名思义,它就是用来接收来自系统和应用中的广播。

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

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

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

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

    [java] view plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    1. @Override  
    2. protected void onDestroy() {  
    3.     super.onDestroy();  
    4.     unregisterReceiver(receiver);  
    5. }  

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

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

    [java] view plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    1. abortBroadcast();  

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

    有序广播(Ordered Broadcast)

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

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

    [java] view plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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 plaincopy
     
    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中定义一个权限:

    [html] view plaincopy
     
    1. <permission android:protectionLevel="normal"  
    2.             android:name="scott.permission.MY_BROADCAST_PERMISSION" />  

    然后声明使用了此权限:

    [html] view plaincopy
     
    1. <uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION" />  

    关于这部分如果有不明白的地方可以参考我之前写过的一篇文章:Android声明和使用权限

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

    我们看到接收是按照顺序的,第一个和第二个都在结果集中加入了自己的标记,并且向优先级低的接收者传递下去。

    既然是顺序传递,试着终止这种传递,看一看效果如何,我们修改FirstReceiver的代码,在onReceive的最后一行添加以下代码:

    [java] view plaincopy
     
    1. abortBroadcast();  

    然后再次运行程序,控制台打印如下:

    此次,只有第一个接收者执行了,其它两个都没能执行,因为广播被第一个接收者终止了。

    上面就是BroadcastReceiver的介绍,下面我将会举几个常见的例子加深一下大家对广播的理解和应用:

    1.开机启动服务

    我们经常会有这样的应用场合,比如消息推送服务,需要实现开机启动的功能。要实现这个功能,我们就可以订阅系统“启动完成”这条广播,接收到这条广播后我们就可以启动自己的服务了。我们来看一下BootCompleteReceiver和MsgPushService的具体实现:

    [java] view plaincopy
     
    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 BootCompleteReceiver extends BroadcastReceiver {  
    9.       
    10.     private static final String TAG = "BootCompleteReceiver";  
    11.       
    12.     @Override  
    13.     public void onReceive(Context context, Intent intent) {  
    14.         Intent service = new Intent(context, MsgPushService.class);  
    15.         context.startService(service);  
    16.         Log.i(TAG, "Boot Complete. Starting MsgPushService...");  
    17.     }  
    18.   
    19. }  
    [java] view plaincopy
     
    1. package com.scott.receiver;  
    2.   
    3. import android.app.Service;  
    4. import android.content.Intent;  
    5. import android.os.IBinder;  
    6. import android.util.Log;  
    7.   
    8. public class MsgPushService extends Service {  
    9.   
    10.     private static final String TAG = "MsgPushService";  
    11.       
    12.     @Override  
    13.     public void onCreate() {  
    14.         super.onCreate();  
    15.         Log.i(TAG, "onCreate called.");  
    16.     }  
    17.       
    18.     @Override  
    19.     public int onStartCommand(Intent intent, int flags, int startId) {  
    20.         Log.i(TAG, "onStartCommand called.");  
    21.         return super.onStartCommand(intent, flags, startId);  
    22.     }  
    23.   
    24.     @Override  
    25.     public IBinder onBind(Intent arg0) {  
    26.         return null;  
    27.     }  
    28. }  

    然后我们需要在AndroidManifest.xml中配置相关信息:

    [html] view plaincopy
     
    1. <!-- 开机广播接受者 -->  
    2. <receiver android:name=".BootCompleteReceiver">  
    3.     <intent-filter>  
    4.         <!-- 注册开机广播地址-->  
    5.         <action android:name="android.intent.action.BOOT_COMPLETED"/>  
    6.         <category android:name="android.intent.category.DEFAULT" />  
    7.     </intent-filter>  
    8. </receiver>  
    9. <!-- 消息推送服务 -->  
    10. <service android:name=".MsgPushService"/>  

    我们看到BootCompleteReceiver注册了“android.intent.action.BOOT_COMPLETED”这个开机广播地址,从安全角度考虑,系统要求必须声明接收开机启动广播的权限,于是我们再声明使用下面的权限:

    [html] view plaincopy
     
    1. <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />  

    经过上面的几个步骤之后,我们就完成了开机启动的功能,将应用运行在模拟器上,然后重启模拟器,控制台打印如下:

    如果我们查看已运行的服务就会发现,MsgPushService已经运行起来了。

    2.网络状态变化

    在某些场合,比如用户浏览网络信息时,网络突然断开,我们要及时地提醒用户网络已断开。要实现这个功能,我们可以接收网络状态改变这样一条广播,当由连接状态变为断开状态时,系统就会发送一条广播,我们接收到之后,再通过网络的状态做出相应的操作。下面就来实现一下这个功能:

    [java] view plaincopy
     
    1. package com.scott.receiver;  
    2.   
    3. import android.content.BroadcastReceiver;  
    4. import android.content.Context;  
    5. import android.content.Intent;  
    6. import android.net.ConnectivityManager;  
    7. import android.net.NetworkInfo;  
    8. import android.util.Log;  
    9. import android.widget.Toast;  
    10.   
    11. public class NetworkStateReceiver extends BroadcastReceiver {  
    12.       
    13.     private static final String TAG = "NetworkStateReceiver";  
    14.       
    15.     @Override  
    16.     public void onReceive(Context context, Intent intent) {  
    17.         Log.i(TAG, "network state changed.");  
    18.         if (!isNetworkAvailable(context)) {  
    19.             Toast.makeText(context, "network disconnected!", 0).show();  
    20.         }  
    21.     }  
    22.       
    23.     /** 
    24.      * 网络是否可用 
    25.      *  
    26.      * @param context 
    27.      * @return 
    28.      */  
    29.     public static boolean isNetworkAvailable(Context context) {  
    30.         ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
    31.         NetworkInfo[] info = mgr.getAllNetworkInfo();  
    32.         if (info != null) {  
    33.             for (int i = 0; i < info.length; i++) {  
    34.                 if (info[i].getState() == NetworkInfo.State.CONNECTED) {  
    35.                     return true;  
    36.                 }  
    37.             }  
    38.         }  
    39.         return false;  
    40.     }  
    41.   
    42. }  

    再注册一下这个接收者的信息:

    [html] view plaincopy
     
    1. <receiver android:name=".NetworkStateReceiver">  
    2.     <intent-filter>  
    3.         <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>  
    4.         <category android:name="android.intent.category.DEFAULT" />  
    5.     </intent-filter>  
    6. </receiver>  

    因为在isNetworkAvailable方法中我们使用到了网络状态相关的API,所以需要声明相关的权限才行,下面就是对应的权限声明:

    [html] view plaincopy
     
    1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>  

    我们可以测试一下,比如关闭WiFi,看看有什么效果。

    3.电量变化

    如果我们阅读软件,可能是全屏阅读,这个时候用户就看不到剩余的电量,我们就可以为他们提供电量的信息。要想做到这一点,我们需要接收一条电量变化的广播,然后获取百分比信息,这听上去挺简单的,我们就来实现以下:

    [java] view plaincopy
     
    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.BatteryManager;  
    7. import android.util.Log;  
    8.   
    9. public class BatteryChangedReceiver extends BroadcastReceiver {  
    10.   
    11.     private static final String TAG = "BatteryChangedReceiver";  
    12.       
    13.     @Override  
    14.     public void onReceive(Context context, Intent intent) {  
    15.         int currLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);  //当前电量  
    16.         int total = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 1);      //总电量  
    17.         int percent = currLevel * 100 / total;  
    18.         Log.i(TAG, "battery: " + percent + "%");  
    19.     }  
    20.   
    21. }  

    然后再注册一下广播接地址信息就可以了:

    [html] view plaincopy
     
    1. <receiver android:name=".BatteryChangedReceiver">  
    2.     <intent-filter>  
    3.         <action android:name="android.intent.action.BATTERY_CHANGED"/>  
    4.         <category android:name="android.intent.category.DEFAULT" />  
    5.     </intent-filter>  
    6. </receiver>  

    当然,有些时候我们是要立即获取电量的,而不是等电量变化的广播,比如当阅读软件打开时立即显示出电池电量。我们可以按以下方式获取:

    [java] view plaincopy
     
    1. Intent batteryIntent = getApplicationContext().registerReceiver(null,  
    2.         new IntentFilter(Intent.ACTION_BATTERY_CHANG
  • 相关阅读:
    凸包模板
    1060E Sergey and Subway(思维题,dfs)
    1060D Social Circles(贪心)
    D
    牛客国庆集训派对Day2
    网络流
    Tarjan算法(缩点)
    莫队分块算法
    计算几何
    hdu5943素数间隙与二分匹配
  • 原文地址:https://www.cnblogs.com/sage-blog/p/4168072.html
Copyright © 2011-2022 走看看