BroadcastReceiver注册方式

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()释放服务

  1. privateMusicReceiver receiver;


  2. @Override

  3. protectedvoid onStart(){

  4. super.onStart();


  5. receiver= new MusicReceiver();

  6. IntentFilterfilter = new IntentFilter();

  7. filter.addAction("com.example.mtc_ly_myweather.Broadcast.MyBroadcasts");

  8. this.registerReceiver(receiver,filter);

  9. }


  10. @Override

  11. protectedvoid onStop(){

  12. this.unregisterReceiver(receiver);

  13. super.onStop();

  14. }

    发送动态广播

    sendBroadcast(newIntent("com.example.mtc_ly_myweather.Broadcast.MyBroadcasts"));//发送动态广播

注册完成广播后都需要一个发送广播的动作才能有接收广播的结果。


3两种注册方式的比较
静态注册方式,由系统来管理receiver,而且程序里的所有receiver,可以在xml里面一目了然
动态注册方式,隐藏在代码中,比较难发现;需要特别注意的是,在退出程序前要记得调用Context.unregisterReceiver()方法。一般在activityonStart()里面进行注册,onStop()里面进行注销。官方提醒,如果在Activity.onResume()里面注册了,就必须在Activity.onPause()注销。


4BroadcastReceiver生命周期

一个BroadcastReceiver对象只有在被调用onReceive(Context,Intent)的才有效,当从该函数返回后,该对象就无效的了,结束生命周期。
因此从这个特征可以看出,在所调用的onReceive(Context,Intent)函数里,不能有过于耗时的操作,不能使用线程来执行。对于耗时的操作,应该在Activity或者Service中去完成。因为当得到其他异步操作所返回的结果时,BroadcastReceiver可能已经无效了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值