您的位置:首页 > 其它

BroadcastReceiver 广播的使用 (activity广播到fragment中,使用静态的没有成功,我就使用动态的 ,是可以的)

2015-10-28 13:17 369 查看
</pre><pre name="code" class="java"><pre name="code" class="java"> //接收广播
public static  class Receiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
String coupons = intent.getExtras().getString("coupons");
Message   ms=new Message();
Bundle  bundle=new Bundle();
ms.what=600;
bundle.putString("coupons",coupons);
ms.setData(bundle);
cHandler.sendMessage(ms);

}
}

//发送广播
Intent intent = new Intent();  //Itent就是我们要发送的内容
intent.putExtra("data", "this is data from broadcast "+Calendar.getInstance().get(Calendar.SECOND));
intent.setAction(flag);   //设置你这个广播的action,只有和这个action一样的接受者才能接受者才能接收广播
sendBroadcast(intent);   //发送广播

//注册广播(动态注册)
receiver=new Receiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.cardvalue.sys.receiver");    //只有持有相同的action的接受者才能接收此广播
registerReceiver(receiver, filter);

//注册广播(静态注册)
<receiver android:name="net.youmi.android.AdReceiver" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_ADDED" />
<data android:scheme="package" />
</intent-filter>
</receiver>

静态和动态的区别
1.动态注册的广播永远要快于静态注册的广播,不管静态注册的优先级设置的多高,不管动态注册的优先级有多低>\
2.动态注册广播不是常驻型广播,也就是说广播跟随activity的生命周期。注意: 在activity结束前,移除广播接收器。
静态注册是常驻型,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行。

<http://www.open-open.com/lib/view/open1342796818088.html   (可以参考)



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: