android_BroadcastReceiver 广播机制

来源:互联网 发布:家庭网络布线交换机 编辑:程序博客网 时间:2024/05/21 09:36
广播接收者( BroadcastReceiver )顾名思义,它就是用来接收来自系统和应用中的广播。它用于接收广播 Intent ,广播 Intent 的发送是通过调用Context.sendBroadcast() 、 Context.sendOrderedBroadcast() 来实现的。通常一个广播 Intent 可以被订阅了此Intent 的多个广播接收者所接收。例如当开机完成后系统会产生一条广播,接收到这条广播就能实现开机启动服务的功能;当网络状态改变时系统会产生一条广播,接收到这条广播就能及时地做出提示和保存数据等操作;当电池电量改变时,系统会产生一条广播,接收到这条广播就能在电量低时告知用户及时保存进度等。
1、创建BroadcastReceiver对象,需要继承android.content.BroadcastReceiver,并实现其onReceive方法。
public class MyReceiver extends BroadcastReceiver {private static final String TAG = "MyReceiver";@Overridepublic void onReceive(Context arg0, Intent intent) {String msg = intent.getStringExtra("msg");Log.i(TAG, msg);}}
在onReceive方法内,可以获取随广播而来的Intent中的数据,并进行处理。
2、创建好BroadcastReceiver之后,还需对其进行注册。
- 静态注册:在AndroidManifest.xml文件中配置
    <receiver android:name=".MyReceiver" >        <intent-filter>            <action android:name="android.intent.action.MY_BROADCAST" />        </intent-filter>    </receiver>
配置好之后,只要是android.intent.action.MY_BROADCAST这个地址的广播,MyReceiver都能够接收的到。注意,这种方式的注册是常驻型的,也就是说当应用关闭后,如果有广播信息传来,MyReceiver也会被系统调用而自动运行。
-动态注册:在代码中动态的指定广播地址并注册,通常我们是在Activity或Service注册一个广播。
class BroadcastReceiverListener implements OnClickListener{public void onClick(View arg0) {// 动态注册// 生成一个BroadcastReceiver对象myReceiver = new MyReceiver();// 生成一个IntentFilter对象IntentFilter filter = new IntentFilter();// 为IntentFilter添加一个actionfilter.addAction("android.intent.action.MY_BROADCAST");// 将broadcastReceiver对象注册到系统当中registerReceiver(myReceiver, filter);}}
registerReceiver是android.content.ContextWrapper类中的方法,Activity和Service都继承了ContextWrapper,所以可以直接调用。在实际应用中,我们在Activity或Service中注册了一个BroadcastReceiver,当这个Activity或Service被销毁时如果没有解除注册,系统会报一个异常,提示我们是否忘记解除注册了。所以,记得在特定的地方执行解除注册操作:
@Override  protected void onDestroy() {      super.onDestroy();      unregisterReceiver(myReceiver);  } 
执行这样行代码就可以解决问题了。注意,这种注册方式与静态注册相反,不是常驻型的,也就是说广播会跟随程序的生命周期。
3、注册好Broadcastreceiver之后,就可以使用它了。
class BroadcastReceiverListener implements OnClickListener{public void onClick(View v) {Intent intent = new Intent("android.intent.action.MY_BROADCAST");intent.putExtra("msg", "hello world!");// intent.setAction("android.intent.action.MY_BROADCAST");sendBroadcast(intent);}}
sendBroadcast也是android.content.ContextWrapper类中的方法,它可以将一个指定地址和参数信息的Intent对象以广播的形式发送出去。

点击按钮,就可以把广播发送出去,并且被MyReceiver接收到。

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

普通广播(Normal Broadcast)
普通广播对于多个接收者来说是完全异步的,通常每个接收者都无需等待即可以接收到广播,接收者相互之间不会有影响。对于这种广播,接收者无法终止广播,即无法阻止其他接收者的接收动作。
新建三个BroadcastReceiver,FirstReceiver、SecondReceiver和ThirdReceiver,演示一下这个过程。
public class FirstReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "FirstReceiver: " + msg);      } }
public class SecondReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "SecondReceiver: " + msg);      }} 
public class ThirdReceiver extends BroadcastReceiver {            private static final String TAG = "NormalBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = intent.getStringExtra("msg");          Log.i(TAG, "ThirdReceiver: " + msg);      }}  
再次点击发送按钮,发送一条广播,控制台打印:

三个接收者都接收到这条广播,如果在三个接收者的onReceive方法的最后一行添加代码,试图终止广播:
abortBroadcast();

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

有序广播(Ordered Broadcast)
有序广播比较特殊,它每次只发送到优先级较高的接收者那里,然后由优先级高的接受者再传播到优先级低的接收者那里,优先级高的接收者有能力终止这个广播。
还是用三个BroadcastReceiver来举例。

public class FirstReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";          @Override    public void onReceive(Context context, Intent intent) {        String msg = intent.getStringExtra("msg");        Log.i(TAG, "FirstReceiver: " + msg);                Bundle bundle = new Bundle();        bundle.putString("msg", msg + "@FirstReceiver");        setResultExtras(bundle);    }} 
public class SecondReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = getResultExtras(true).getString("msg");          Log.i(TAG, "SecondReceiver: " + msg);                    Bundle bundle = new Bundle();          bundle.putString("msg", msg + "@SecondReceiver");          setResultExtras(bundle);      }}
public class ThirdReceiver extends BroadcastReceiver {            private static final String TAG = "OrderedBroadcast";            @Override      public void onReceive(Context context, Intent intent) {          String msg = getResultExtras(true).getString("msg");          Log.i(TAG, "ThirdReceiver: " + msg);      }}
在FirstReceiver和SecondReceiver中最后都使用了setResultExtras方法将一个Bundle对象设置为结果集对象,传递到下一个接收者那里,这样以来,优先级低的接收者可以用getResultExtras获取到最新的经过处理的信息集合。
然后,我们需要为三个接收者注册广播地址,我们修改一下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> 
现在这三个接收者的<intent-filter>多了一个android:priority属性,并且依次减小。这个属性的范围在-1000到1000,数值越大,优先级越高。
然后修改一下发送广播的代码:
class BroadcastReceiverListener implements OnClickListener{public void onClick(View arg0) {Intent intent = new Intent("android.intent.action.MY_BROADCAST");intent.putExtra("msg", "hello world!");// intent.setAction("android.intent.action.MY_BROADCAST");// sendBroadcast(intent);sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION");}}
使用sendOrderedBroadcast方法发送有序广播时,需要一个权限参数,如果为null则表示不要求接收者声明指定的权限,如果不为null,则表示接收者若要接收此广播,需声明指定权限。这样做是从安全角度考虑的,例如系统的短信就是有序广播的形式,一个应用可能是具有拦截垃圾短信的功能,当短信到来时它可以先接受到短信广播,必要时终止广播传递,这样的软件就必须声明接收短信的权限。
所以在AndroidMainfest.xml中定义一个权限:
<permission android:protectionLevel="normal" android:name="scott.permission.MY_BROADCAST_PERMISSION" />  
然后声明使用了此权限:
<uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION" />  
然后我们点击发送按钮发送一条广播,控制台打印如下:

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

既然是顺序传递,试着终止这种传递,看一看效果如何,我们修改FirstReceiver的代码,在onReceive的最后一行添加abortBroadcast(); 再次运行程序,此次,只有第一个接收者执行了,其它两个都没能执行,因为广播被第一个接收者终止了。

more--->http://blog.csdn.net/liuhe688/article/details/6955668

Android声明和使用权限 http://blog.csdn.net/liuhe688/article/details/6417983

欢迎交流 http://blog.csdn.net/ycwol/article/details/45665567

1 1
原创粉丝点击