android资料收集Android技术知识Android开发经验谈

LocalBroadcastManager源码解析

2018-03-08  本文已影响22人  雷l阵l雨

LocalBroadcastManager是Android Support包提供了一个工具类,用于在同一个应用内的不同组件间发送广播,广播数据在本应用内传播,相比在系统内发送全局广播,安全性高,效率也高,广播接收者接收消息是在主线程,所以可以在广播接收者里面更新UI,但不能做耗时操作,以免阻塞UI。

LocalBroadcastManager基本用法

注册广播接收者
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
发送广播
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
取消注册广播接收者
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);

LocalBroadcastManager.getInstance(this)

使用单例模式创建LocalBroadcastManager对象,在LocalBroadcastManager的构造函数中创建了一个Handler,且在主线程中处理消息。

public static LocalBroadcastManager getInstance(Context context) {
    //单例模式
    synchronized (mLock) {
        if (mInstance == null) {
            //创建LocalBroadcastManager对象
            //把外部传进来的Context,转化成了ApplicationContext,有效的避免了当前Context的内存泄漏的问题
            mInstance = new LocalBroadcastManager(context.getApplicationContext());
        }
        return mInstance;
    }
}

private LocalBroadcastManager(Context context) {
    mAppContext = context;
    //创建Handler,由context.getMainLooper()可知, 这个Handler是在主线程中创建的
    mHandler = new Handler(context.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                //收到MSG_EXEC_PENDING_BROADCASTS类型消息,执行executePendingBroadcasts方法处理广播
                case MSG_EXEC_PENDING_BROADCASTS:
                    executePendingBroadcasts();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };
}

注册广播接收者registerReceiver

mReceivers的类型是HashMap<BroadcastReceiver, ArrayList<IntentFilter>>,key为注册的广播接收者,value为该广播接收者对应的IntentFilter的集合。mActions的类型是HashMap<String, ArrayList<ReceiverRecord>>,key为action,value为该action对应的ReceiverRecord的集合。注册广播就是以要注册的广播接收者BroadcastReceiver为key,把该广播接收者对应的IntentFilter的集合ArrayList<IntentFilter>>放入mReceivers,以IntentFilter匹配的action为key,把该action对应的ReceiverRecord的集合ArrayList<ReceiverRecord>存入mActions。

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    synchronized (mReceivers) {
        //ReceiverRecord封装了IntentFilter和BroadcastReceiver
        ReceiverRecord entry = new ReceiverRecord(filter, receiver);
        //一种广播接收者BroadcastReceiver可以对应多个IntentFilter
        ArrayList<IntentFilter> filters = mReceivers.get(receiver);
        if (filters == null) {
            filters = new ArrayList<IntentFilter>(1);
            mReceivers.put(receiver, filters);
        }
        //将filter存入filters集合,也即存入对应receiver的mReceivers
        filters.add(filter);
        //一个Intent Filter中可声明多个action
        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);
            }
            //将entry存入entries集合,也即存入对应action的mActions
            entries.add(entry);
        }
    }
}

取消注册广播接收者unregisterReceiver

与注册广播接收者相对应,取消注册广播接收者就是从mReceivers中移除该广播接收者对应的IntentFilter的集合ArrayList<IntentFilter>>,从mActions中移除该广播接收者对应的所有IntentFilter匹配的action和相关ReceiverRecord。

public void unregisterReceiver(BroadcastReceiver receiver) {
    synchronized (mReceivers) {
        //从mReceivers中移除receiver对应的IntentFilter的集合,并返回该集合
        ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
        if (filters == null) {
            return;
        }
        for (int i=0; i<filters.size(); i++) {
            IntentFilter filter = filters.get(i);
            for (int j=0; j<filter.countActions(); j++) {
                String action = filter.getAction(j);
                //获取action对应的ReceiverRecord的集合
                ArrayList<ReceiverRecord> receivers = mActions.get(action);
                if (receivers != null) {
                    for (int k=0; k<receivers.size(); k++) {
                        if (receivers.get(k).receiver == receiver) {
                            //从receivers中当前移除receiver对应的ReceiverRecord
                            receivers.remove(k);
                            k--;
                        }
                    }
                    if (receivers.size() <= 0) {
                        //action对应的集合receivers无数据时,从mActions移除
                        mActions.remove(action);
                    }
                }
            }
        }
    }
}

发送广播sendBroadcast

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);
        //获取intent的action对应的ReceiverRecord的集合
        ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
        if (entries != null) {
            if (debug) Log.v(TAG, "Action list: " + entries);

            //保存匹配的ReceiverRecord
            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);

                //如果已经匹配过并加入receivers里了,就执行下一次循环
                if (receiver.broadcasting) {
                    if (debug) {
                        Log.v(TAG, "  Filter's target already added");
                    }
                    continue;
                }

                //将filter与intent的信息进行匹配
                int match = receiver.filter.match(action, type, scheme, data,
                        categories, "LocalBroadcastManager");
                //如果匹配成功就把receiver加入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);
                    }
                }
            }

            if (receivers != null) {
                //将broadcasting置为false,这样下一个Intent到来时,ReceiverRecord才有机会重新加入到receivers中
                for (int i=0; i<receivers.size(); i++) {
                    receivers.get(i).broadcasting = false;
                }
                //创建BroadcastRecord对象,并加入到mPendingBroadcasts中
                //BroadcastRecord包含intent以及与其匹配的ReceiverRecord的集合
                mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                //如果主线程消息队列中没有MSG_EXEC_PENDING_BROADCASTS类型的消息,则发送该消息
                if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                    mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                }
                return true;
            }
        }
    }
    return false;
}

从上面可以看出,sendBroadcast方法的参数是一个intent,先从获取与其匹配的ReceiverRecord的集合,把intent与该集合封装成BroadcastRecord对象,把它加入mPendingBroadcasts集合,然后通过Handler发送MSG_EXEC_PENDING_BROADCASTS消息,调用executePendingBroadcasts()方法。

executePendingBroadcasts方法

executePendingBroadcasts方法从mPendingBroadcasts集合中取出BroadcastRecord,通过br.receivers.get(j).receiver获取BroadcastReceiver,并调用BroadcastReceiver的onReceive方法。

private void executePendingBroadcasts() {
    //不停的执行,直到return
    while (true) {
        BroadcastRecord[] brs = null;
        synchronized (mReceivers) {
            final int N = mPendingBroadcasts.size();
            if (N <= 0) {
                return;
            }
            //保存要处理的BroadcastRecord
            brs = new BroadcastRecord[N];
            //将集合mPendingBroadcasts的数据都放到数组brs里
            mPendingBroadcasts.toArray(brs);
            //清空mPendingBroadcasts,若下次while循环时没有新数据加入,就会退出循环
            mPendingBroadcasts.clear();
        }
        for (int i=0; i<brs.length; i++) {
            BroadcastRecord br = brs[i];
            for (int j=0; j<br.receivers.size(); j++) {
                //调用BroadcastReceiver的onReceive方法
                br.receivers.get(j).receiver.onReceive(mAppContext, br.intent);
            }
        }
    }
}

最后,我们可以看出LocalBroadcastManager本质是通过Handler机制发送消息到主线程,然后调用BroadcastReceiver的onReceive方法的。


欢迎关注.jpg
上一篇 下一篇

猜你喜欢

热点阅读