阅读 100

本地广播LocalBroadcastManager基本使用与源码解析

原文链接: www.jianshu.com

BroadcastReceiver

BroadcastReceiver是Android四大组件之一,我们都比较熟悉,称它为“广播”
Android中的广播就类似于电台广播,一个广播可以有N个接收者。这是一个典型的发布——订阅模式,也可以叫做观察者模式。
广播机制最大的特点就是发送发并不关心接收方是否接收到数据,也不关心接收方是如何处理数据的,通过这样的形式达到接收双方的完全解耦。

BroadcastReceiver是一个全局的(可跨进程)的广播,也就是说所有应用都可收到你发送的BroadcastReceiver。这可能会带来安全隐患,比如其他应用恶意模拟发送广播、获取隐私数据等等。

在BroadcastReceiver源码类注释中有如下文字:

If you don't need to send broadcasts across applications, consider using this class with LocalBroadcastManager instead of the more general facilities described below. This will give you a much more efficient implementation (no cross-process communication needed) and allow you to avoid thinking about any security issues related to other applications being able to receive or send your broadcasts.

意思大概是如果你不需要跨进程发送广播,请考虑使用LocalBroadcastManager替代BroadcastReceiver,这样我们就可以避免其他应用程序能够接收或发送你的应用程序的BroadcastReceiver所带来的安全问题

LocalBroadcastManager的基本使用

  • 注册广播
 LocalBroadcastManager.getInstance(context).registerReceiver(receiver,intentFilter);
复制代码
  • 反注册广播
 LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
复制代码
  • 发送广播
 LocalBroadcastManager.getInstance(context).sendBroadcast(newIntent());
复制代码

LocalBroadcastManager 源码解析

代码量比较少,我先用大白话说一遍,有个印象之后,看代码就好理解了

大体框架就是两个内部类、三个集合、一个Handler、注册广播的方法、反注册广播的方法、发送广播的方法、通知接收者的方法。

  • 两个内部类用于承载一些广播数据,如IntentFilter、BroadcastReceiver等
  • 三个集合就是将承载着数据的内部类存储起来,功能:存储注册的接收者、方便在需要的时候获取对象,比如获取接受者并回调onReceive方法等
  • Handler用于在主线程发送并接收消息,调用executePendingBroadcasts()方法为接受者回调onReceive方法
  • 注册广播的方法:用内部类封装数据,并存入集合
  • 反注册广播的方法:从集合中删除对应的数据
  • 发送广播的方法:获取到Intent中携带的数据,与集合中保存的数据进行匹配,将匹配的保存到集合中,通过handler发送消息回调executePendingBroadcasts()方法为接受者回调onReceive方法
  • 通知接收者的方法:从集合中获取注册的BroadcastReceiver对象,调用其onReceive方法
public class LocalBroadcastManager {

    /**
     * 内部类ReceiverRecord 用于保存IntentFilter和BroadcastReceive
     */
    private static class ReceiverRecord {
        final IntentFilter filter;
        final BroadcastReceiver receiver;
        boolean broadcasting;

        ReceiverRecord(IntentFilter _filter, BroadcastReceiver _receiver) {
            filter = _filter;
            receiver = _receiver;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder(128);
            builder.append("Receiver{");
            builder.append(receiver);
            builder.append(" filter=");
            builder.append(filter);
            builder.append("}");
            return builder.toString();
        }
    }

    /**
     * 内部类BroadcastRecord 承载着ReceiverRecord集合,用于发送广播时获取BroadcastReceiver对象
     */
    private static class BroadcastRecord {
        final Intent intent;
        final ArrayList<ReceiverRecord> receivers;

        BroadcastRecord(Intent _intent, ArrayList<ReceiverRecord> _receivers) {
            intent = _intent;
            receivers = _receivers;
        }
    }

    private static final String TAG = "LocalBroadcastManager";
    private static final boolean DEBUG = false;

    private final Context mAppContext;

    //以BroadcastReceiver对象为key,IntentFilter集合为value 在注册广播接收器时添加 用于以后方便取消注册广播接收器
    private final HashMap<BroadcastReceiver, ArrayList<IntentFilter>> mReceivers
            = new HashMap<BroadcastReceiver, ArrayList<IntentFilter>>();
    //以Action字符串为key,以装载着IntentFilter和BroadcastReceive的内部类ReceiverRecord为value,用于发送广播后得到广播接收器
    private final HashMap<String, ArrayList<ReceiverRecord>> mActions
            = new HashMap<String, ArrayList<ReceiverRecord>>();
    //存储装载着ReceiverRecord集合的内部类BroadcastRecord的集合 用于发送广播时回调BroadcastReceiver的onReceive方法
    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 LocalBroadcastManager mInstance;

    //单例模式创建
    public static LocalBroadcastManager getInstance(Context context) {
        synchronized (mLock) {
            if (mInstance == null) {
                mInstance = new LocalBroadcastManager(context.getApplicationContext());
            }
            return mInstance;
        }
    }

    private LocalBroadcastManager(Context context) {
        mAppContext = context;
        //核心  使用一个主线程Looper的Handler 用于完成广播的消息处理
        //也就是说 onReceive接收广播的时候 是处于主线程中
        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);
                }
            }
        };
    }

    /**
     * 注册广播接收器
     * 
     */
    public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
        synchronized (mReceivers) {
            //承载IntentFilter和BroadcastReceiver的内部类,会将其存储于mActions集合,方便根据action查找广播接收器
            ReceiverRecord entry = new ReceiverRecord(filter, receiver);

            //将BroadcastReceiver和IntentFilter存入mReceivers集合中,方便取消广播监听器
            ArrayList<IntentFilter> filters = mReceivers.get(receiver);
            if (filters == null) {
                filters = new ArrayList<IntentFilter>(1);
                mReceivers.put(receiver, filters);
            }
            filters.add(filter);

            //将action和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);
            }
        }
    }

    /**
     * 取消广播接收器
     */
    public void unregisterReceiver(BroadcastReceiver receiver) {
        synchronized (mReceivers) {
            //移除掉mActions集合中的该BroadcastReceiver对象
            ArrayList<IntentFilter> filters = mReceivers.remove(receiver);
            if (filters == null) {
                return;
            }

            //根据mActions存储的IntentFilter集合将mActions集合中相关action对应的ReceiverRecord也删掉
            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);
                    ArrayList<ReceiverRecord> receivers = mActions.get(action);
                    if (receivers != null) {
                        for (int k=0; k<receivers.size(); k++) {
                            if (receivers.get(k).receiver == receiver) {
                                receivers.remove(k);
                                k--;
                            }
                        }
                        if (receivers.size() <= 0) {
                            mActions.remove(action);
                        }
                    }
                }
            }
        }
    }

    /**
     * 发送广播
     *     1.获取到要发送的Intent包含的信息
     *     2.从注册的接收器中找到与之匹配的接收器,存储到集合中
     *     3.通过Handler在主线程回调注册的接收器的onReceive方法
     */
    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);

            // 根据action从mActions集合中获取到ReceiverRecord集合
            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);

                    //broadcasting是内部类ReceiverRecord的一个属性,用于防止重复加入receiver到receivers集合
                    //被加入receivers集合时赋值为true,遍历结束后将改属性全部赋值为false
                    if (receiver.broadcasting) {
                        if (debug) {
                            Log.v(TAG, "  Filter's target already added");
                        }
                        continue;
                    }

                    //用断定filter是否匹配
                    int match = receiver.filter.match(action, type, scheme, data,
                            categories, "LocalBroadcastManager");
                    if (match >= 0) {   //匹配
                        if (debug) Log.v(TAG, "  Filter matched!  match=0x" +
                                Integer.toHexString(match));
                        if (receivers == null) {
                            receivers = new ArrayList<ReceiverRecord>();
                        }
                        //将匹配的receiver加入receivers集合
                        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) {
                    //添加结束,将所有receiver对象的broadcasting属性赋值为false
                    for (int i=0; i<receivers.size(); i++) {
                        receivers.get(i).broadcasting = false;
                    }
                    //封装进BroadcastRecord中,并添加到mPendingBroadcasts集合
                    mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                    //若主线程队列中没有MSG_EXEC_PENDING_BROADCASTS,则发送该消息进行onReceive回调
                    if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                        mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                    }
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 发送同步广播 
     * 指的是在一次广播的发送完成之前,不会同时发送其他广播
     */
    public void sendBroadcastSync(Intent intent) {
        if (sendBroadcast(intent)) {
            executePendingBroadcasts();
        }
    }


    /**
     * 回调注册的BroadcastReceiver的onReceive方法
     */
    private void executePendingBroadcasts() {
        while (true) {
            BroadcastRecord[] brs = null;
            synchronized (mReceivers) {
                final int N = mPendingBroadcasts.size();
                if (N <= 0) {
                    return;
                }
                brs = new BroadcastRecord[N];
                //将所有匹配的集合这保存到BroadcastRecord数组中
                mPendingBroadcasts.toArray(brs);
                //将该集合清除 如果本次循环结束前未添加新的对象到该集合,那么下次循环将被return
                mPendingBroadcasts.clear();
            }

            //遍历回调匹配的BroadcastReceiver的onReceive方法
            for (int i=0; i<brs.length; i++) {
                BroadcastRecord br = brs[i];
                for (int j=0; j<br.receivers.size(); j++) {
                    br.receivers.get(j).receiver.onReceive(mAppContext, br.intent);
                }
            }
        }
    }
}
复制代码

看完源码,我们会发现,BroadcastReceiver的跨进程通信是依赖Binder机制来完成的,而LocalBroadcastManager这个不跨进程的广播并没有那么复杂,说白了就是单例模式的LocalBroadcastManager将广播接收者存储到集合中,发送广播时去集合找到对应的接受者,配合了Handler的使用回调onReceive对象罢了

利与弊

它的好处是:

  • 仅在本应用内广播,不用担心数据泄露与其他应用模拟发送广播,比BroadcastReceiver更安全
  • 效率比使用Binder的BroadcastReceiver高

相对而言,缺点就是:

  • 不能跨进程通信。这就是它的双刃剑啊
  • 不能用于系统Action,例如电量、Wifi状态等

总而言之,就是根据自己的实际情况去选择适合的工具,这样才能让它们都“工作”在自己真正应该在的岗位上,才能发挥出最大的价值!

文章分类
Android
文章标签