• LocalBroadcastManager是什么?
  • LocalBroadcastManager原理是怎样的?
  • 小结

LocalBroadcastManager是什么?

  LocalBroadcastManager是android中本地广播的核心类。那什么是本地广播呢?它是一种在会在app内部传播的信息通信方式。因为其只在app内部传播,所以它安全;又因为其并不想系统级别的广播那样要有IPC,所以它高效。



  但本地广播也有它的缺点,接收信息的只能是Receiver及其继承类的对象,而不能像总线类通信方式那样,只要是注册的类对象,都可以接收数据。

LocalBroadcastManager原理是怎样的?

  简单地讲,其原理就是:将广播接收者receiver注册到LocalBroadcastReceiver对象中的一个数据结构里(HashMap),发送广播时匹配到能够接收该广播的Receiver,因为发送广播有可能是在子线程中,为了保证接收广播的逻辑在主线程中执行,匹配到receiver之后通过持有MainLooper的Handler切换线程到主线程中去执行receiver的onReceiver方法。


1. registerReceiver和unregisterReceiver

  在LocalBroadcastManager类中比较重要的方法有两个:registerReceiver(BroadcastReceiver receiver, IntentFilter filter)和sendBroadcast(Intent intent)。首先说一下registerReceiver方法:

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    synchronized (mReceivers) {
        //将ReceiverRecord对象存储到mReceivers中
        ReceiverRecord entry = new ReceiverRecord(filter, receiver);
        ArrayList<ReceiverRecord> filters = mReceivers.get(receiver);
        if (filters == null) {
            filters = new ArrayList<>(1);
            mReceivers.put(receiver, filters);
        }
        filters.add(entry);
        //将ReceiverRecord对象存储到mActions中,ReceiverRecord对象可能
        //会出现在mActions中的多个地方
        for (int i=0; i<filter.countActions(); i++) {
            String action = filter.getAction(i);
            ArrayList<ReceiverRecord> entries = mActions.get(action);
            if (entries == null) {
                entries = new ArrayList<ReceiverRecord>(1);
                mActions.put(action, entries);
            }
            entries.add(entry);
        }
    }
}

  通过这个方法的名字可以知道,该方法就是一个注册广播接收者的方法。具体都做了哪些事情呢?
    1. 将receiver和intentFilter封装成ReceiverRecord对象;
    2. 将ReceiverRecord对象存储到一个以receiver为key、以ReceiverRecord列表为value的map中,此map名为mReceivers,是一个成员字段;
    3. 将ReceiverRecord对象存储到一个以action为key,以ReceiverRecord列表为value的map中,此map名为mActions,也是一个成员字段;

  对于mReceivers,纵观整个LocalBroadcastManager类,感觉它并没有参与到核心流程receiver.onReceive方法的回调中,它的作用仅限于作为锁对象来同步以及在unregisterReceiver(BroadcastReceiver receiver)方法的调用中通过receiver拿到receiver对象的intentFilter。

  unregisterReceiver(BroadcastReceiver receiver)方法中都有哪些操作呢?首先,就是拿到IntentFilter对象,拿到此对象后就可以其包含的所有action;其次,遍历所有的action,删除掉mActions这个map中receiver为当前要反注册的receiver的ReceiverRecord对象。

public void unregisterReceiver(BroadcastReceiver receiver) {
    synchronized (mReceivers) {
        //从mReceivers中删除掉receiver对应的ReceiverRecord对象
        final ArrayList<ReceiverRecord> filters = mReceivers.remove(receiver);
        if (filters == null) {
            return;
        }
        //上面根据receiver对象拿到了IntentFilter对象,
        //下面遍历所有IntentFilter对象包含的所有action,
        //找到这些action所对应的ReceiverRecord对象,
        //如果这些ReceiverRecord对象中的Receiver对象与receiver相同,
        //则要移除这个ReceiverRecord对象
        for (int i=filters.size()-1; i>=0; i--) {
            final ReceiverRecord filter = filters.get(i);
            filter.dead = true;
            for (int j=0; j<filter.filter.countActions(); j++) {
                final String action = filter.filter.getAction(j);
                final ArrayList<ReceiverRecord> receivers = mActions.get(action);
                if (receivers != null) {
                    for (int k=receivers.size()-1; k>=0; k--) {
                        final ReceiverRecord rec = receivers.get(k);
                        if (rec.receiver == receiver) {
                            rec.dead = true;
                            receivers.remove(k);
                        }
                    }
                    if (receivers.size() <= 0) {
                        mActions.remove(action);
                    }
                }
            }
        }
    }
}

  对于mActions,这个map就是LocalBroadcastManager中的核心数据结构了。在registerReceiver中,以intentFilter中声明的action为key,存储ReceiverRecord对象。因为intentFilter中本身就可能有多个action,所以有可能在mActions中总共会有多个该ReceiverRecord对象。在发送广播时,intent应该是只能设定一个action,通过该action匹配mActions中的ReceiverRecord,匹配到就执行。当然匹配时,不仅匹配action,还会匹配intentFilter中的其它值,比如category、mimeType等;

2. sendBroadcast

  上面讲述了LocalBroadcastManager的registerReceiver和unregisterReceiver方法,下面开始说LocalBroadcastManager类中另一个比较重要的方法:sendBroadcast(Intent intent)

public boolean sendBroadcast(Intent intent) {
        synchronized (mReceivers) {
            //获取到广播intent中的所有信息
            final String action = intent.getAction();
            final String type = intent.resolveTypeIfNeeded(
                    mAppContext.getContentResolver());
            final Uri data = intent.getData();
            final String scheme = intent.getScheme();
            final Set<String> categories = intent.getCategories();

            final boolean debug = DEBUG ||
                    ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
            if (debug) Log.v(
                    TAG, "Resolving type " + type + " scheme " + scheme
                    + " of intent " + intent);

            //从mActions中拿到其对应的所有ReceiverRecord对象,
            //筛选出与广播intent中信息匹配的ReceiverRecord对象并
            //存储到receivers这个列表数据结构中
            ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
            if (entries != null) {
                if (debug) Log.v(TAG, "Action list: " + entries);

                ArrayList<ReceiverRecord> receivers = null;
                for (int i=0; i<entries.size(); i++) {
                    ReceiverRecord receiver = entries.get(i);
                    if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);

                    if (receiver.broadcasting) {
                        if (debug) {
                            Log.v(TAG, "  Filter's target already added");
                        }
                        continue;
                    }

                    //从当前遍历到的ReceiverRecord对象中拿到intentFilter与
                    //广播intent进行匹配校验
                    int match = receiver.filter.match(action, type, scheme, data,
                            categories, "LocalBroadcastManager");
                    //匹配了就加入到receivers中
                    if (match >= 0) {
                        if (debug) Log.v(TAG, "  Filter matched!  match=0x" +
                                Integer.toHexString(match));
                        if (receivers == null) {
                            receivers = new ArrayList<ReceiverRecord>();
                        }
                        receivers.add(receiver);
                        receiver.broadcasting = true;
                    } else {
                        if (debug) {
                            String reason;
                            switch (match) {
                                case IntentFilter.NO_MATCH_ACTION: reason = "action"; break;
                                case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break;
                                case IntentFilter.NO_MATCH_DATA: reason = "data"; break;
                                case IntentFilter.NO_MATCH_TYPE: reason = "type"; break;
                                default: reason = "unknown reason"; break;
                            }
                            Log.v(TAG, "  Filter did not match: " + reason);
                        }
                    }
                }

                //将可接收此广播的ReceiverRecord对象集合封装到BroadcastRecord对象中,
                //加入到mPendingBroadcasts里面
                if (receivers != null) {
                    for (int i=0; i<receivers.size(); i++) {
                        receivers.get(i).broadcasting = false;
                    }
                    mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                    //利用Handler切换到线程
                    if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                        mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                    }
                    return true;
                }
            }
        }
        return false;
    }

  如注释所示,sendBroadcast方法中主要做的事情是:
    1. 根据广播intent中的action,从mActions这个map中拿到所有可接收此广播的ReceiverRecord对象;
    2. 将这些ReceiverRecord对象封装在BroadcastRecord对象中;
    3. 将BroadcastRecord对象存储在mPendingBroadcasts集合中,之后通过Handler切换线程。

3. 回调广播接收者的onReceive方法

  通过Handler切换线程之后,下面就是对onReceive方法的回调了

private void executePendingBroadcasts() {
    while (true) {
        final BroadcastRecord[] brs;
        synchronized (mReceivers) {
            final int N = mPendingBroadcasts.size();
            if (N <= 0) {
                return;
            }
            //转换成数组
            brs = new BroadcastRecord[N];
            mPendingBroadcasts.toArray(brs);
            mPendingBroadcasts.clear();
        }
        //逐一遍历BroadcastRecord对象,
        //从BroadcastRecord对象中拿到所有的可处理广播的接收者,
        //检测一下状态,逐一回调receiver对象的onReceive方法。
        for (int i=0; i<brs.length; i++) {
            final BroadcastRecord br = brs[i];
            final int nbr = br.receivers.size();
            for (int j=0; j<nbr; j++) {
                final ReceiverRecord rec = br.receivers.get(j);
                if (!rec.dead) {
                    rec.receiver.onReceive(mAppContext, br.intent);
                }
            }
        }
    }
}

  切换到主线程的操作也很清晰,遍历所有的mPendingBroadcasts,取出所有BroadcastRecord中的Receiver对象,经过sendBroadcast方法中的过滤,这里的Receiver对象都是可接收此广播的Receiver对象,直接调用这些Receiver对象的onReceive方法即可。

小结

  整个LocalBroadcastManager类其实代码量很少,只有300多行。其核心数据结构是一个map,注册的广播接收者与intentFilter封装成一个Record对象,存储在该map中,该map的key为intentFilter的action;在发送广播时,根据此广播的action从map中匹配到可接收此广播的广播接收者,然后回调这些广播接收者的onReceive方法。仅此而已。



  核心思想其实就只有上面这些,只不过还要处理并发、反注册、切换线程等,增加了其它一些代码。