BroadcastReceiver注册方式
1静态注册
AndroidManifest.xml中,application里面,定义receiver并设置要接收的action
<receiverandroid:name="com.example.mtc_ly_myweather.Broadcast.MyBroadcast">
<intent-filter>
<actionandroid:name="com.example.mtc_ly_myweather.CRAZY_BROADCAST"/>
</intent-filter>
</receiver>
发送静态广播
Intentintent = newIntent();
intent.putExtra("msg","MyBroad");
intent.setAction("com.example.mtc_ly_myweather.CRAZY_BROADCAST");
sendBroadcast(intent);
2动态注册
Activity中,需在onStart()中调用registerReceiver()进行注册和在onStop中调用unregisterReceiver()释放服务
-
privateMusicReceiver receiver;
-
-
@Override
-
protectedvoid onStart(){
-
super.onStart();
-
-
receiver= new MusicReceiver();
-
IntentFilterfilter = new IntentFilter();
-
filter.addAction("com.example.mtc_ly_myweather.Broadcast.MyBroadcasts");
-
this.registerReceiver(receiver,filter);
-
}
-
-
@Override
-
protectedvoid onStop(){
-
this.unregisterReceiver(receiver);
-
super.onStop();
-
}
发送动态广播
sendBroadcast(newIntent("com.example.mtc_ly_myweather.Broadcast.MyBroadcasts"));//发送动态广播
注册完成广播后都需要一个发送广播的动作才能有接收广播的结果。
3两种注册方式的比较
静态注册方式,由系统来管理receiver,而且程序里的所有receiver,可以在xml里面一目了然
动态注册方式,隐藏在代码中,比较难发现;需要特别注意的是,在退出程序前要记得调用Context.unregisterReceiver()方法。一般在activity的onStart()里面进行注册,onStop()里面进行注销。官方提醒,如果在Activity.onResume()里面注册了,就必须在Activity.onPause()注销。
4、BroadcastReceiver生命周期
一个BroadcastReceiver对象只有在被调用onReceive(Context,Intent)的才有效,当从该函数返回后,该对象就无效的了,结束生命周期。
因此从这个特征可以看出,在所调用的onReceive(Context,Intent)函数里,不能有过于耗时的操作,不能使用线程来执行。对于耗时的操作,应该在Activity或者Service中去完成。因为当得到其他异步操作所返回的结果时,BroadcastReceiver可能已经无效了。