这种方式不用在配置文件加东西
变量声明
- LocalBroadcastManager broadcastManager;
- IntentFilter intentFilter;
- BroadcastReceiver mReceiver;
广播注册,可以写在Activity(onCreate),也可以写在Fragment(onActivityCreated)里。
- broadcastManager = LocalBroadcastManager.getInstance(getActivity());
- intentFilter = new IntentFilter();
- intentFilter.addAction("android.intent.action.CART_BROADCAST");
- mReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent){
-
- }
- };
- broadcastManager.registerReceiver(mReceiver, intentFilter);
发送广播
- Intent intent = new Intent("android.intent.action.CART_BROADCAST");
- LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
当然,和正常广播一样,也要在对应的生命周期中反注册掉:
- @Override
- protected void onDestroy() {
- super.onDestroy();
- broadcastManager.unregisterReceiver(mReceiver);
- }
Fragment使用LocalBroadcastManager接收广播消息
原文:http://www.cnblogs.com/Free-Thinker/p/6135376.html