前言:
在Android中,Broadcast是一种广泛运用的在应用程序之间传输信息的机制。BroadcastReceiver设计的
初衷是从全局考虑可以方便应用程序和系统、应用程序之间、应用程序内的通信。但是有时候只是给进程
内部发送广播也需要绕一大圈,有没有简单的方法呢? LocalBroadcastManager。
LocalBroadcastManager是Android Support包提供了一个工具,用于在同一个应用内的不同组件间发送
Broadcast。LocalBroadcastManager也称为局部通知管理器,这种通知的好处是安全性高,效率也高,
适合局部通信,可以用来代替Handler更新UI。
LocalBroadcastManager使用也很简单,四个步骤如下,
1,获取LocalBroadcastManager对象,
LocalBroadcastManager mlocalBroadcastManager = LocalBroadcastManager.getInstance( this ) ;
2, 注册广播接收器
mlocalBroadcastManager.registerReceiver( broadcastReceiver , intentFilter );
3, 发送广播
mlocalBroadcastManager.sendBroadcast( intent ) ;
4, 取消注册广播接收器
mlocalBroadcastManager.unregisterReceiver( broadcastReceiver );
LocalBroadcastManager的全局变量如下,
private final Context mAppContext; //上下文对象
private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
= new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
private final HashMap<String, ArrayList<ReceiverRecord>> mActions
= new HashMap<String, ArrayList<ReceiverRecord>>();
private final ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<BroadcastRecord>();
static final int MSG_EXEC_PENDING_BROADCASTS = 1;
private final Handler mHandler;
private static final Object mLock = new Object();//同步锁
private static LocalBroad