当前位置: 代码迷 >> Android >> android四大组件之播音接收器BroadcastReceiver
  详细解决方案

android四大组件之播音接收器BroadcastReceiver

热度:92   发布时间:2016-04-28 02:12:22.0
android四大组件之广播接收器BroadcastReceiver

Android有一个非常重要的特性,就是广播.也可以将广播看做是通信机制.  Android四大组件: Activity, service, broadcastReceiver 和contentProvider, 只有Activity和service有完整的生命周期, 其他 broadcastReceiver 和contentProvider 都没有.  broadcastReceiver 本质上是一个监听器, 负责监听系统应用发出的广播(BroadCast). 


broadcastReceiver 有个onReceive(Context context, Intent intent)方法, 这个方法是广播接收器broadcastReceiver接收广播的地方,Intent可以看做是特定的广播介质.不同的intent会触发不同的广播接收器,然后怎么处理就放在onReceive() (省略写法)  中去实现.  


发送广播

上面说到intent是"广播介质", 将intent放到发广播的方法中去就ok:

       public class broadCastTest extends Activity	{		private Button btn_send;				@Override		public void onCreate(Bundle savedInstanceState)		{			super.onCreate(savedInstanceState);			setContentView(R.id.act_main);						btn_send = (Button)findViewById(R.id.btn_send);			btn_send.setOnClickListener(new OnClickListener() {								@Override				public void onClick(View v) {					// 发送广播					sendMyBroadCast();				}			});					}						private void sendMyBroadCast()		{			Intent intent = new Intent();			//设置intent的Action属性,这个会使intent找到与之对应的广播接收器			intent.setAction("com.test.action.My_Test_BroadCast");			//给Intent设置可传递的消息			intent.putExtra("msgKey", "消息内容");			//发送广播			sendBroadcast(intent);		}			}


接收广播(注册广播接收器)

1,在代码中注册配置广播接收器

注册广播接收器这里,配合上面发送广播的例子来看,会好理解一些.

在代码中调用BroadCastReceiver的registerReceiver( BroadCastReceiver receiver, IntentFilter filter )方法去指定特定的intent广播对应特定的广播接收器:

//里面内容填写上面发送广播的Action内容IntentFilter filter = new IntentFilter("com.test.action.My_Test_BroadCast"); //MyReceiver 是继承了BroadCastReceiver自定义实现的广播接收器MyReceiver,//最好这样做,因为这样才能区分不同的广播接收器用于对应不同的广播MyReceiver receiver = new MyReceiver();//注册完毕,MyReceiver广播接收器现在是对应接收 Action为"com.test.action.My_Test_BroadCast"的intent广播registerReceiver(receiver, filter);


2,在AndroidManifest.xml 文件中注册配置

<receiver android:name="com.test.MyReceiver">	<intent-filter>		<!-- 指定MyReceiver 对应Action为"com.test.action.My_Test_BroadCast"的intent广播 -->		<action android:name="com.test.action.My_Test_BroadCast">	</intent-filter></receiver>

上面两种方式,都能注册MyReceiver这个广播接收器专门响应Action为"com.test.action.My_Test_BroadCast" 的intent 广播. 一旦发送广播中使用sendBroadCast()发送了广播,MyReceiver就会响应,并在onReceive()中去接收处理.


强调一些点

1, 很多人用在跳转Activity的时候都使用过intent来传递一些内容,如果intent没有找到对应的Activity.class 就会报错 class can not be found之类的错误.但在广播中,使用Intent传递广播,即使intent没有找到对应的广播接收器, 却不会报错.过一段时间,这个广播会被系统自行销毁.


2, 每发送一次广播,广播每次找到广播接收器BroadCastReceiver,都会新建一个BroadCastReceiver实例,并不会说之前已经使用过这个BroadCastReceiver实例了就继续沿用旧的BroadCastReceiver实例.因为每次BroadCastReceiver实例在onReceive()中接收并处理完广播后就会销毁这个实例.既然都不存在了, 所以下次再发同样的广播,也会继续创建新的BroadCastReceiver实例.


3, 不要把耗时的操作放在onReceive() 中,切记!  BroadCastReceiver实例的onReceive()只适合进行一些非常轻量化的操作,比如弹框提示"网络中断了",比如进行一些简单的数据处理等等. 因为超过一定时间( 旧版本这个上限是10秒,新版貌似短一些 ),如果onReceive()方法还没有结束,系统就会强制销毁这个实例,甚至报错.


4, 如果在Activity中注册了广播接收器,那么在退出Activity前,要先取消注册这些广播接收器.在onDestroy()中类似的:

@Overridepublic void onDestroy(){	// 取消注册	getApplicationContext().unregisterReceiver(receiver);	super.onDestroy();}


5, 区别普通广播和有序广播.  上面说的都是普通广播, 普通在于, 发送广播和接收广播两者并不是同步的, 也就是说是异步的.你怎么发送是你的事,人家广播接收器怎么接收处理也和发送广播无关,所以有同时发送几个广播出去, 先发的可能迟一些才被响应, 后发的广播有可能会更早被响应.  而有序广播比较特殊, 它对广播接收器的权限区分了优先级, 广播会先发送到优先级高的那里去,依次直至最后一个优先级最低的广播接收器.而且优先级高的接收器有能力结束广播,使广播不再往优先级比自己低的接收器那里传递.

关于有序广播,上个例子: 

首先在AndroidManifest.xml加入权限:

<uses-permission android:name="scott.permission.MY_BROADCAST_PERMISSION" /> 

定义3个广播接收器:

          public class A_Receiver extends BroadcastReceiver {  	    @Override  	    public void onReceive(Context context, Intent intent) {  	        String msg = intent.getStringExtra("key");  	        //此处Bundle可用于向优先级低的接收器传递一些信息	        Bundle bundle = new Bundle();  	        bundle.putString("msgKey_A", msg);  	        setResultExtras(bundle);	        //如果最后一行加入abortBroadcast(),则广播不再往下一个接收器传播	        //abortBroadcast(); 	    }  	  	} 		public class B_Receiver extends BroadcastReceiver {  	    @Override  	    public void onReceive(Context context, Intent intent) {  	        String msg = getResultExtras(true).getString("msgKey_A");  	        //同上理	        Bundle bundle = new Bundle();  	        bundle.putString("msgKey_B", msg);  	        setResultExtras(bundle);  	    }  	  	} 			public class C_Receiver extends BroadcastReceiver {  	    @Override  	    public void onReceive(Context context, Intent intent) {  	        String msg = getResultExtras(true).getString("msgKey_B");  	        //进行其他处理...	    }  	    	}


下面注册广播接收器:

   <receiver android:name="com.test.A_Receiver">      <!-- priority="xxx"的值越大,优先级越高,两个接收器的值不要一样大,范围在-1000到1000 -->    <intent-filter android:priority="100">          <action android:name="android.intent.action.MY_TEST_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>      </receiver>      <receiver android:name="com.test.B_Receiver">      <intent-filter android:priority="99">          <action android:name="android.intent.action.MY_TEST_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>      </receiver>      <receiver android:name="com.test.C_Receiver">      <intent-filter android:priority="98">          <action android:name="android.intent.action.MY_TEST_BROADCAST"/>          <category android:name="android.intent.category.DEFAULT" />      </intent-filter>      </receiver>


发送有序广播:

private void sendBroadCast(){	Intent intent = new Intent("android.intent.action.MY_TEST_BROADCAST");  	intent.putExtra("key", "hello receiver.");  	sendOrderedBroadcast(intent, "scott.permission.MY_BROADCAST_PERMISSION"); }

广播机制是Android系统非常核心非常重要的一部门,配合service一起使用,能够实现强大的后台.使应用更加流畅和高效,





  相关解决方案