Android原生的registerReceiver与LocalBroadcastManager的区别,以及为什么会存在这样的区别?

  • Andord原生的registerReceiver方式是可以跨进程使用的,因为它使用的是Binder机制,它的registerBroadcast,unregisterReceiver和sendBroadcast都是在ActivityManagerService中实现的,所以它能支持跨进程广播。

  • LocalBroadcastManager方式实际上是通过单例LocalBroadcastManager对象中的几个变量存储Broadcast,IntentFilter

private final HashMap> mReceivers
            = new HashMap>();
private final HashMap> mActions
            = new HashMap>();

private final ArrayList mPendingBroadcasts
            = new ArrayList();

一旦跨进程,这个LocalBroadcastManager就不是同一个对象了。
当sendBroadcast时,是使用Handler发送Message的方式,实现事件回调的

if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
    mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
}

Handler是在构造方法中创建的

 private LocalBroadcastManager(Context context) {
 mAppContext = context;
 mHandler = new Handler(context.getMainLooper()) {

      @Override
      public void handleMessage(Message msg) {
           switch (msg.what) {
           case MSG_EXEC_PENDING_BROADCASTS:
                executePendingBroadcasts();
                break;
                default:
                super.handleMessage(msg);
           }
     }
   };
}
 private void executePendingBroadcasts() {
        while (true) {
            BroadcastRecord[] brs = null;
            synchronized (mReceivers) {
                final int N = mPendingBroadcasts.size();
                if (N <= 0) {
                    return;
                }
                brs = new BroadcastRecord[N];
                mPendingBroadcasts.toArray(brs);
                mPendingBroadcasts.clear();
            }
            for (int i=0; i

你可能感兴趣的:(Android原生的registerReceiver与LocalBroadcastManager的区别,以及为什么会存在这样的区别?)