BroadcastReceiver详解

简介:

详解

 分类:
5、andriod开发 (148) 
 

目录(?)[+]

 

前言:这个月写的博客文章数量比较多,因为刚入门的缘故吧,多总结,由浅入深,等后面更深入了再给大家写续篇。

 

学之广在于不倦,不倦在于固志。 ——晋·葛洪­

(学问的渊博在于学习时不知道厌倦,而学习不知厌倦在于有坚定的目标)

 

一、概述

BroadcastReceiver:直译是“广播接收者”,所以它的作用是用来接收发送过来的广播的。

那我们有必要知道:什么是广播。广播,我的理解就是系统中消息的一种变种;就是当一个事件发生时,比如,系统突然断网,系统就发一个广播消息给所有的接收者,所有的接收者在得到这个消息之后,就知道,啊哦,现在没网络了,我的程序应该怎么办,比如显示默认图片、提示用户等。前面,我们说了,BroadcastReceiver就是一个广播消息接收者。

另外我还要提一下,广播之间信息的传递是通过Intent对象来传递的;在《详解Intent》系列文章中,我讲了,Intent调用分为显示调用的隐式调用两种,由于这里能通知到所有的接收者,所以肯定不能利用显示调用,只有利用隐式调用Intent对象了。(这里的隐式调用,并不是真正意义上的Intent隐式调用,因为Intent隐式调用,当出现很多匹配应用时,会以列表形式提示用户选择一个启动,而这里不同的地方在于,当有很多匹配项时,会给所有的匹配项都发一个消息,我说隐式调用,只是方便大家理解构造Intent的方法,即必须利用构造隐式Intent的方法来构造)

 

二、注册相关

 

1、静态注册实例程序 

大家可能会问,什么叫静态注册实例程序,先不要管上面的标题,慢慢往下看,后面在讲动态注册时会再提到。

先构造一个接收器:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MyReceiver extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         // TODO Auto-generated method stub  
  8.   
  9.         String msg = intent.getStringExtra("msg");    
  10.         Log.i(TAG, "MyReceiver:"+msg);    
  11.           
  12.     }  
  13.   
  14. }  
直接派生自BroadcastReceiver,在OnReceive()函数中进行处理即可,我们前面说了,广播的传递是靠Intent的,OnReceive的第二个参数,就是广播传过来的Intent,因为后面我们在发送广播时,会利用PutStringExtra放进去一个标识为msg的字符串,所以这里我们可以利用GetStringExtra把这个字符串取出来。然后用Log标记下这个类接收到了这个消息,以便我们跟踪。
大家可能会想,就这么着,就能收到广播了?当然不是,上面我们说了,通过隐式Intent来发送广播的,我们肯定要匹配这个Intent啊,匹配Intent的术语是Activity中的,在广播这里,叫要注册,也就是要注册一下,什么样的Intent能接收。

 

MyReceiver的广播接收 注册代码如下:(静态注册)

 

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  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:name:对应接收器的类名;我们自定义的类名叫MyReceiver ,所以这里写".MyReceiver "

 

intent-filter标签里,同样是必须的两项:action和category;我在这里自定义了action的名字,等下隐式发送通过时,就是利用匹配action来接收通知的。

此时的AndroidManifest.xml全部内容为:

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.test_brocast_blog"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="14"  
  9.         android:targetSdkVersion="14" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name=".MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.           
  26.         <receiver android:name=".MyReceiver">  
  27.             <intent-filter>  
  28.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  29.                 <category android:name="android.intent.category.DEFAULT" />  
  30.             </intent-filter>  
  31.         </receiver>  
  32.     </application>  
  33.   
  34. </manifest>  
这里特别注意一个<activity> 标签与<receiver>标签的构造。完全相同!!!!!!!
完全相同体现在:

 

 

  • 1、所处位置:都直属<application>标签;
  • 2、参数构造基本一样;都有android:name,都有<intent-filter>;
  • 3、都是通过Intent传递参数,也都是通过Intent进行匹配!!!!

 

这说明了一个问题:receiver是activity的变种!!!!!我没有研究源码,但仅从这些相同点来看,他们肯定是从一个共同的类派生出来的。(猜想)

最后是发送广播:

我们在主页面加一个Button,当点击Button时发送广播消息。

布局文件如下:(activity_main.xml)

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context="com.example.test_brocast_blog.MainActivity" >  
  6.   
  7.    <Button  
  8.         android:id="@+id/sent_btn"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:text="发送Broadcast" />  
  12.   
  13. </RelativeLayout>  
代码如下:(MainActivity.java)
[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.       
  8.         Button btn= (Button)findViewById(R.id.sent_btn);  
  9.         btn.setOnClickListener(new View.OnClickListener() {  
  10.               
  11.             @Override  
  12.             public void onClick(View v) {  
  13.                 // TODO Auto-generated method stub  
  14.                 send();  
  15.             }  
  16.         });  
  17.           
  18.     }  
  19.       
  20.     public void send() {  
  21.         Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  22.         intent.putExtra("msg", "hello receiver.");  
  23.         sendBroadcast(intent);  
  24.     }  
  25. }  
真正的发送代码在send()函数中,在这个函数中可以看到,我们通过传进去刚才注册的MyRecevier的action,来构造一个隐式Intent,然后利用PutExtra放进去一个额外信息(这个不是必须的,我们仅仅是为了跟踪这个消息传到了哪里去,在《详解Intnent》系统文章中有讲怎样构造一个隐式Intent),与StartActivity不同的是,这里利用的是sendBroadcast(intent)来发送这个Intent;
效果图:

 

 

这里注意一下应用名!!!!(com.example.test_brocast_blog)后面会用到。

 

2、动态注册实例程序

前面,我们说了静态注册,什么叫静态注册呢,就是利用XML来注册。

相反,利用代码来注册的就叫动态注册。

静态注册和动态注册是有区别的,主要体现在接收上。

静态注册的程序,无论该程序是否启动,都会当广播到来时接收,并处理。而动态注册的程序只有在程序运行时才会收到广播消息,程序不运行了,它就收不到了。

动态注册的代码如下:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. MyReceiver receiver = new MyReceiver();  
  2. IntentFilter filter = new IntentFilter();  
  3. filter.addAction("android.intent.action.MY_BROADCAST");  
  4.           
  5. registerReceiver(receiver, filter);  
同样,首先生成我们要接收的类的实例,然后利用IntentFilter来声明他可以匹配的广播类型(这里利用动作来匹配),最后利用registerReceiver(receiver, filter);来注册,即利用当哪种类型的Intent广播到来时,要调用MyReceiver类。

 

注意:发送广播之前,要先注册,不然根本没有接收者匹配,当然,不注册接收者也不会出现任何错误或警告,只是发送一个没有任何接收者的广播播毫无意义。
下面我们新建一个项目,取名叫:Test_Brocast_Blog_Dynamic

同样,写一个MyRecever类来接收广播,MyRecever类内容不变:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MyReceiver extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         // TODO Auto-generated method stub  
  8.   
  9.         String msg = intent.getStringExtra("msg");    
  10.         Log.i(TAG, msg);    
  11.     }  
  12.   
  13. }  
然后同样,给MainActivity布局里添加一个Button,当点击Button时发送广播。布局文件与上面一样,这里我只写代码:
[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.           
  8.       //在发送之前,确定在代码的某个位置已经动态注册  
  9.         MyReceiver receiver = new MyReceiver();  
  10.         IntentFilter filter = new IntentFilter();  
  11.         filter.addAction("android.intent.action.MY_BROADCAST");  
  12.                   
  13.         registerReceiver(receiver, filter);  
  14.           
  15.           
  16.         //发送广播  
  17.         Button btn= (Button)findViewById(R.id.sent_btn);  
  18.         btn.setOnClickListener(new View.OnClickListener() {  
  19.               
  20.             @Override  
  21.             public void onClick(View v) {  
  22.                 // TODO Auto-generated method stub  
  23.                 send();  
  24.             }  
  25.         });  
  26.           
  27.           
  28.           
  29.     }  
  30.       
  31.     public void send() {  
  32.         Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  33.         intent.putExtra("msg", "hello receiver.");  
  34.         sendBroadcast(intent);  
  35.     }  
  36.   
  37. }  
在OnCreate()里在注册广播接收者,即告诉系统,当这个广播到来时,用MyReciver来接收。然后点击发送按钮来发送广播。
注:(在运行这个程序之前,先把静态注册的APP装到手机上,这是下面得出结论的前提)

 

结果如下:

                                操作界面 

结果:

咦?怎么出来两条信息?

也就是说有两个接收者接收到了这条广播,但我们这里只注册了一个MyRecever实例啊。

对的,看应用名称就可以看得出,这是两个不同的应用,有一个是静态注册的(com.example.test_brocast_blog),所以静态注册的程序不管是否启动,都可以收得到匹配的广播的,并对这个广播操作。

如果想试一下,动态注册的代码能不能收到广播,可以反过来一下,运行静态注册的程序,把动态注册的程序关掉,看出来几条Log?答案肯定是一条!因为我们都知道动态注册的代码在程序不运行时是收不到广播的。

 

三、普通广播与有序广播

普通广播是指大家等级都是一样的,当广播到来时,都能一块接收到,并没有接收的先后顺序。由于是一同接收到的,所以一个接收者是没有办法阻止另一个接收者接收这个广播的。

有序广播是指接收是按一定的优先级顺序来接收的,优先级高的先收到,并可以对广播进行操作后,再传给下一个接收者,当然也可以不传,如果不传的话,后面的接收者就都收不到这个广播了。

普通广播

(在运行这个程序之前,先把手机上前两个APP全部删除,以免影响结果)

首先我们建三个接收者,并对他们全部静态注册。三个接收者的代码分别如下:

FirstRecever:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class FirstRecever extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.     @Override  
  5.     public void onReceive(Context context, Intent intent) {  
  6.         // TODO Auto-generated method stub  
  7.   
  8.         String msg = intent.getStringExtra("msg");    
  9.         Log.i(TAG, "FirstRecever:"+msg);    
  10.     }  
  11. }  
SecondRecever:

 

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class SecondRecever extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.     @Override  
  5.     public void onReceive(Context context, Intent intent) {  
  6.         // TODO Auto-generated method stub  
  7.   
  8.         String msg = intent.getStringExtra("msg");    
  9.         Log.i(TAG, "SecondRecever:"+msg);    
  10.     }  
  11. }  

 

MyReceiver

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MyReceiver extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         // TODO Auto-generated method stub  
  8.   
  9.         String msg = intent.getStringExtra("msg");    
  10.         Log.i(TAG, "MyReceiver:"+msg);    
  11.     }  
  12. }  
注册代码如下:(AndroidManifest.xml)
[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.test_brodcast"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="14"  
  9.         android:targetSdkVersion="14" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name=".MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.               
  25.         </activity>  
  26.         <!-- 分别注册这三个接收器 -->  
  27.          <receiver android:name=".MyReceiver">  
  28.             <intent-filter>  
  29.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  30.                 <category android:name="android.intent.category.DEFAULT" />  
  31.             </intent-filter>  
  32.         </receiver>  
  33.           
  34.          <receiver android:name=".FirstRecever">  
  35.             <intent-filter>  
  36.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  37.                 <category android:name="android.intent.category.DEFAULT" />  
  38.             </intent-filter>  
  39.         </receiver>  
  40.           
  41.          <receiver android:name=".SecondRecever">  
  42.             <intent-filter>  
  43.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  44.                 <category android:name="android.intent.category.DEFAULT" />  
  45.             </intent-filter>  
  46.         </receiver>  
  47.           
  48.     </application>  
  49.   
  50. </manifest>  
同样,我们在MainActivity中添加一个Button,当点击按钮时发送广播,MainActivity代码如下:

 

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.           
  8.         Button btn= (Button)findViewById(R.id.sent_btn);  
  9.         btn.setOnClickListener(new View.OnClickListener() {  
  10.               
  11.             @Override  
  12.             public void onClick(View v) {  
  13.                 // TODO Auto-generated method stub  
  14.                 send();  
  15.             }  
  16.         });  
  17.           
  18.     }  
  19.       
  20.     public void send() {  
  21.         Intent intent = new Intent("android.intent.action.MY_BROADCAST");  
  22.         intent.putExtra("msg", "hello receiver.");  
  23.         sendBroadcast(intent);  
  24.     }  
  25.   
  26. }  
运行程序,结果:

可见,三个全都收到了广播。

 

有序广播(无访问权限版)

首先有序广播与普通广播的不同点在发送和接收都有不同。

首在发送有序广播:

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.       
  8.         Button btn= (Button)findViewById(R.id.sent_btn);  
  9.         btn.setOnClickListener(new View.OnClickListener() {  
  10.               
  11.             @Override  
  12.             public void onClick(View v) {  
  13.                 // TODO Auto-generated method stub  
  14.                 send();  
  15.             }  
  16.         });  
  17.           
  18.     }  
  19.       
  20.     public void send() {  
  21.           
  22.         Intent intent = new Intent("android.intent.action.MY_BROADCAST");    
  23.         intent.putExtra("msg", "hello receiver.");    
  24.         sendOrderedBroadcast(intent, null);  //没有添加权限  
  25.     }  
  26. }  
在前面的各个例子中,我们发送广播都是用的:sendBroadcast(intent); 而这里却用的是:sendOrderedBroadcast(intent, null);  

 

对这个函数的官方解释是:

 

public abstract void sendOrderedBroadcast (Intent intent, String receiverPermission)

Added in  API level 1

Broadcast the given intent to all interested BroadcastReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See BroadcastReceiver for more information on Intent broadcasts.

Parameters
intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission (optional) String naming a permissions that a receiver must hold in order to receive your broadcast. If null, no permission is required.
其中第二个参数是指定接收者必须拥有的接收权限,如果设为NUll,就是不需要接收权限,所有匹配的Receiver都能接收到。我们这里先不需要权限试试看,下面再举个需要权限的例子。
接收端

 

我们上面说了,接收端必须是有序的,是有优先级的,这种优先级是在注册时配置的,比如:

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <receiver android:name=".FirstRecever">  
  2. <intent-filter android:priority="10">  
  3.     <action android:name="android.intent.action.MY_BROADCAST"/>  
  4.     <category android:name="android.intent.category.DEFAULT" />  
  5. </intent-filter>  
  6. lt;/receiver>  
与上面静态注册的不同在于,在Intent-filter中添加一个android:priority="10"属性,这个就是接收器优先级,数字越大的接收器,优先级越高,越先接到广播。
同样,上面我们三个类FirstRecever、SecondRecever和MyReceiver 的注册文件代码如下 :

 

 

[html]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.testbroast_order"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="14"  
  9.         android:targetSdkVersion="14" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name=".MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.           
  26.   
  27.          <receiver android:name=".FirstRecever">  
  28.             <intent-filter android:priority="10">  
  29.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  30.                 <category android:name="android.intent.category.DEFAULT" />  
  31.             </intent-filter>  
  32.         </receiver>  
  33.           
  34.          <receiver android:name=".SecondRecever">  
  35.             <intent-filter android:priority="9">  
  36.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  37.                 <category android:name="android.intent.category.DEFAULT" />  
  38.             </intent-filter>  
  39.         </receiver>  
  40.           
  41.         <receiver android:name=".MyReceiver">  
  42.             <intent-filter android:priority="8">  
  43.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  44.                 <category android:name="android.intent.category.DEFAULT" />  
  45.             </intent-filter>  
  46.         </receiver>  
  47.         <!-- 接收优先级逐级降低 -->  
  48.     </application>  
  49.   
  50. </manifest>  
最后是代码部分
前面我也曾提到,在一个接收器收到发来的Intent后,可以对其进行更改,对发送来的广播Intent进行修改是利用setResultExtras(bundle);  函数来实现的。

 

 

public final void setResultExtras (Bundle extras)

Added in  API level 1

Change the current result extras of this broadcast; only works with broadcasts sent through Context.sendOrderedBroadcast. This is a Bundle holding arbitrary data, whose interpretation is up to the broadcaster. Can be set to null. Calling this method completely replaces the current map (if any).

This method does not work with non-ordered broadcasts such as those sent with Context.sendBroadcast

 

Parameters
extras The new extra data map; may be null.
翻译一下:

 

这个函数是用来改变当前广播传来的Extra额外信息的;它只能通过Context.sendOrderedBroadcast.发送过来的广播有效;它使用Bundle来传递任意的数据,而这些数据只有接收器(broadcaster)才能解析。当然也可以把它设置为NULL,这样,它就把传来的数据映射全部清空了。

参数:

extras:新的数据映射,可以为空。

从上面的优先级可以看出,这里三个类的接收顺序是这样的:FirstRecever-》SecondRecever-》MyReceiver

下面看看FirstRecever如何利用setResultExtras来改变传来的Msg信息:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class FirstRecever extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.     @Override  
  5.     public void onReceive(Context context, Intent intent) {  
  6.         // TODO Auto-generated method stub  
  7.   
  8.         //先获得传过来的MSG  
  9.         String msg = intent.getStringExtra("msg");    
  10.         Log.i(TAG, "FirstRecever:"+msg);    
  11.           
  12.         //更改广播数据  
  13.          Bundle bundle = new Bundle();    
  14.          bundle.putString("msg", msg + "@FirstReceiver");    
  15.          setResultExtras(bundle);    
  16.     }  
  17. }  
首先,我们利用getStringExtra()获得传过来的msg消息,然后利用bundle重新封装一个以“msg”为key的消息,把"@FirstReceiver"添加到消息里,表示经过了这里。

最后利用setResultExtras(bundle);  修改当前的结果集。

如果想终止消息往下一个接收器传递,可以使用:abortBroadcast();  //终止消息再传递

这里有一个疑问:我利用setResultExtras(bundle); 修改传送结果,对原来广播过来的数据有影响吗?下面我们就在SecondRecever中做个测试

 

下面看看另外两个接收器代码:SecondRecever

 

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class SecondRecever extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.     @Override  
  5.     public void onReceive(Context context, Intent intent) {  
  6.         // TODO Auto-generated method stub          
  7.        
  8.        //先获得广播过来的MSG  
  9.         String broadcast_msg = intent.getStringExtra("msg");    
  10.         Log.i(TAG, "SecondRecever--broadcast_msg:"+broadcast_msg);    
  11.           
  12.         //接收通过setResultExtras传过来的msg  
  13.         String msg = getResultExtras(true).getString("msg");    
  14.         Log.i(TAG, "SecondReceiver: " + msg);    
  15.           
  16.         //修改setResultExtras传来的结果  
  17.         Bundle bundle = new Bundle();    
  18.         bundle.putString("msg", msg + "@SecondReceiver");    
  19.         setResultExtras(bundle);    
  20.     }  
  21. }  
这里先通过intent.getStringExtra("msg");  获得广播过来的数据;

 

然后再利用getResultExtras(true).getString("msg");  获得上一级传过来的setResultExtras(bundle);  里的数据;
最后重新将bundle里的数据中添加"@SecondReceiver"做个标记;

最后,MyReceiver:

 

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MyReceiver extends BroadcastReceiver {  
  2.   
  3.     private static final String TAG = "MyReceiver";    
  4.       
  5.     @Override  
  6.     public void onReceive(Context context, Intent intent) {  
  7.         // TODO Auto-generated method stub  
  8.   
  9.         String msg = getResultExtras(true).getString("msg");    
  10.         Log.i(TAG, "MyReceiver: " + msg);    
  11.     }  
  12. }  

 

到这就所有就序了,运行下代码:

从结果可以看出:通过setResultExtras(bundle);  传递的数据是不会更改原生广播的数据的。也只是原来广播数据中额外添加的数据。

 

有序广播(添加访问权限版)

前面我们看到在sendOrderedBroadcast(intent, null);  中,第二个参数可以设定访问权限,在上个例子中,我们并没有加入访问权限,下面我们就发送一个带权限的广播:

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.   
  8.         Button btn= (Button)findViewById(R.id.sent_btn);  
  9.         btn.setOnClickListener(new View.OnClickListener() {  
  10.               
  11.             @Override  
  12.             public void onClick(View v) {  
  13.                 // TODO Auto-generated method stub  
  14.                 send();  
  15.             }  
  16.         });  
  17.           
  18.     }  
  19.       
  20.     public void send() {  
  21.           
  22.         Intent intent = new Intent("android.intent.action.MY_BROADCAST");    
  23.         intent.putExtra("msg", "hello receiver.");    
  24.         sendOrderedBroadcast(intent, "harvic.broadcast.perssion");   
  25.     }  
  26. }  
这段代码中,我们利用 sendOrderedBroadcast(intent, "harvic.broadcast.perssion"); 发送一个必须拥有"harvic.broadcast.perssion"权限的接收器才能接收到我们的广播;
然后我们要在接收器中加入声明使用权限的代码:

 

有关权限的声明与使用,可以参考这篇文章:《声明、使用与自定义权限》

首先创建一个"harvic.broadcast.perssion"权限

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <permission android:name="harvic.broadcast.perssion" android:protectionLevel="normal"></permission>   
然后是底部声明,我们要使用这个权限:

 

 

[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <uses-permission  android:name="harvic.broadcast.perssion"/>  
所以总体的代码如下:
[java]  view plain  copy
 
在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.testbroadcast_order_perssion"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="14"  
  9.         android:targetSdkVersion="14" />  
  10.     <permission android:name="harvic.broadcast.perssion" android:protectionLevel="normal"></permission>   
  11.   
  12.     <application  
  13.         android:allowBackup="true"  
  14.         android:icon="@drawable/ic_launcher"  
  15.         android:label="@string/app_name"  
  16.         android:theme="@style/AppTheme" >  
  17.         <activity  
  18.             android:name=".MainActivity"  
  19.             android:label="@string/app_name" >  
  20.             <intent-filter>  
  21.                 <action android:name="android.intent.action.MAIN" />  
  22.   
  23.                 <category android:name="android.intent.category.LAUNCHER" />  
  24.             </intent-filter>  
  25.         </activity>  
  26.           
  27.           
  28.         <receiver android:name=".FirstRecever" >  
  29.             <intent-filter android:priority="10">  
  30.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  31.                 <category android:name="android.intent.category.DEFAULT" />  
  32.             </intent-filter>  
  33.         </receiver>  
  34.           
  35.          <receiver android:name=".SecondRecever" >  
  36.             <intent-filter android:priority="9">  
  37.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  38.                 <category android:name="android.intent.category.DEFAULT" />  
  39.             </intent-filter>  
  40.         </receiver>  
  41.           
  42.         <receiver android:name=".MyReceiver" >  
  43.             <intent-filter android:priority="8">  
  44.                 <action android:name="android.intent.action.MY_BROADCAST"/>  
  45.                 <category android:name="android.intent.category.DEFAULT" />  
  46.             </intent-filter>  
  47.         </receiver>  
  48.         <!-- 接收优先级逐级降低 -->  
  49.           
  50.     </application>  
  51.      
  52.     <!-- 如果不添加使用权限声明,那么接收器会拒绝接受消息的,所以在Log中不会有任何显示 -->  
  53.     <uses-permission  android:name="harvic.broadcast.perssion"/>  
  54.   
  55. </manifest>  
其它接收器代码不变,运行之后:

 


有个地方要注意:即便像我们现在这样,自己的应用发出广播给自己接收,但如果不声明使用权限,是不能接收到广播的。这点与Activity的权限机制不一样,在Activity中,只要在同一个应用中相互App跳转,是不需要声明使用权限的,权限的限制只针对其它应用调用此Activity。

好啦,这篇文章到这就结束了。本篇内容比较多,涉及到的代码工程也比较多,现将相关源码列表如下:

1、静态注册源码
2、动态注册源码
3、普通接收源码
4、有序广播(无访问权限)源码
5、有序广播(添加访问权限)源码
6、本文所用图片

 

注意:在OnReceive中保存传过来值的问题:

如果有下面一段伪代码:

class xxxx{

private int mData=1;

public void onReceive(Context context, Intent intent)

Log.d("tag",mData + "");

mData = intent.getIntExtra("intdata",-1);

}

如果我们通过intent传过来的值保存在mData中,在下次再来的时候先打出来mData的值,会发现,每次打出来的都是1,所以根本没有办法通过成员变量保存onReceive中传过来的值。

 

源码下载地址:http://download.csdn.net/detail/harvic880925/7797869

请大家尊重原创者版权,转载请标明出处:http://blog.csdn.net/harvic880925/article/details/38710901 谢谢!

 




    本文转自 一点点征服   博客园博客,原文链接:http://www.cnblogs.com/ldq2016/p/6249632.html,如需转载请自行联系原作者




相关文章
|
21天前
|
XML 监控 Android开发
Activity详解2
Activity详解
30 1
|
10月前
|
API Android开发 开发者
Android四大组件-BroadcastReceiver
Android四大组件-BroadcastReceiver
87 0
|
设计模式 Android开发
Android四大组件之BroadcastReceiver(一)
BroadcastReceiver是Android四大组件之一,在app开发中被广泛应用到,那什么是广播呢?
250 0
|
Android开发
Android四大组件之BroadcastReceiver(四)
两个方面来解决BroadcastReceiver存在的安全隐患,分别是自定义广播权限和使用LocalBroadcastManager。
102 1
|
Android开发
Android四大组件之BroadcastReceiver(二)
接下来讲 BroadcastReceiver的使用,主要讲如何动态注册广播,如何静态注册广播,已经两者之间的区别。
122 0
|
安全 Android开发
Android四大组件之BroadcastReceiver(三)
接下来讲一下有序广播中对广播的拦截、有序广播与标准广播的区别、广播的安全性问题
184 1
|
Java Android开发
2-AII--BroadcastReceiver有序广播
零、前言 先讲个场景小故事: 从前,有个小男孩捡到一颗漂亮的石头,他想去卖,价格1元。 男孩(Boy)大喊:"我有一个漂亮的石头,只卖1元",一个石匠买了这个石头。
1100 0
|
Android开发
BroadcastReceiver的源码分析
android提供了广播机制,通过BroadcastReceiver可以在不同的进程间传递消息。类似于观察者模式,A应用通过注册广播表示A对消息subject感兴趣,当B应用发出subject类型的消息的时候,A应用就能收到对应的消息。
1285 0

热门文章

最新文章