LocalBradcastManager源码分析

基本使用

LocalBroadcastManager是Android Support包提供了一个工具,用于在同一个应用内的不同组件间发送BroadcastReceiver。
android.support.v4.content.LocalBroadcastManager工具类,可以实现在自己的进程内进行局部广播发送与注册,使用它比直接通过sendBroadcast(Intent)发送系统全局广播有以下几个好处:

  • 因广播数据在本应用范围内传播,不用担心隐私数据泄露的问题
  • 不用担心别的应用伪造广播,造成安全隐患
  • 相比在系统内发送全局广播,它更高效

广播的注册

var mLocalBroadcastManager: LocalBroadcastManager? = null
var mReceiver: BroadcastReceiver? = null

val filter = IntentFilter()
filter.addAction("action")
mReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {

    }
}
mLocalBroadcastManager = LocalBroadcastManager.getInstance(this)
mLocalBroadcastManager?.registerReceiver(mReceiver!!, filter)

反注册

mLocalBroadcastManager.unregisterReceiver(mReceiver!!)

广播的发送

LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent("action"));

源码解析

注册广播时,会将BroadcastReceiver和IntentFilter保存到HashMap中。发送广播时,则根据IntentFilter的Action值从已保存的HashMap找到对应接受者,并发送Handler消息去执行receiver的onReceive方法。同步方法则直接调用receiver的onReceive方法。

成员变量

private final HashMap> mReceivers
        = new HashMap>();//用于保存注册的BroadcastReceiver和IntentFilter
private final HashMap> mActions
        = new HashMap>();//用于保存action和ReceiverRecord集合

private final ArrayList mPendingBroadcasts
        = new ArrayList();//用于保存待分发的广播

BroadcastRecord

主要是对Intent和ReceiverRecord的封装

private static class BroadcastRecord {
    final Intent intent;
    final ArrayList receivers;

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

ReceiverRecord

主要是对IntentFilter和BroadcastReceiver的封装

private static class ReceiverRecord {
    final IntentFilter filter;
    final BroadcastReceiver receiver;
    boolean broadcasting;

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

registerReceiver

注册广播

public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
    synchronized (mReceivers) {
        ReceiverRecord entry = new ReceiverRecord(filter, receiver);
        ArrayList filters = mReceivers.get(receiver);
        if (filters == null) {
            filters = new ArrayList(1);
            mReceivers.put(receiver, filters);//添加receiver和IntentFilter
        }
        filters.add(filter);
        for (int i=0; i entries = mActions.get(action);
            if (entries == null) {
                entries = new ArrayList(1);
                mActions.put(action, entries);//添加action和ReceiverRecord
            }
            entries.add(entry);
        }
    }
}
  • 首先通过查找mReceivers中找到已经注册的IntentFilter,并添加进ArrayList
  • 遍历IntentFilter的action,将action对应的ReceiverRecord添加进ArrayList

其实注册动作就是向HashMap中添加元素,进行保存

unregisterReceiver

反注册广播

    public void unregisterReceiver(BroadcastReceiver receiver) {
        synchronized (mReceivers) {
            ArrayList filters = mReceivers.remove(receiver);//根据receiver得到ArrayList并从mReceivers中移除
            if (filters == null) {
                return;
            }
            for (int i=0; i receivers = mActions.get(action);//获取ReceiverRecord的集合
                    if (receivers != null) {
                        for (int k=0; k为空代表这个action没有注册的广播了,进行移除
                        }
                    }
                }
            }
        }
    }

反注册的过程与注册的过程相反,主要是从两个HashMap移除数据

sendBroadcast

广播的发送,代码比较长,我把无关紧要的debug代码和log删除了

    public boolean sendBroadcast(Intent intent) {
        synchronized (mReceivers) {
            //得到Intent中的action、type、data、scheme和categories
            final String action = intent.getAction();
            final String type = intent.resolveTypeIfNeeded(mAppContext.getContentResolver());
            final Uri data = intent.getData();
            final String scheme = intent.getScheme();
            final Set categories = intent.getCategories();
            ArrayList entries = mActions.get(intent.getAction());//从mActions得到ReceiverRecord的集合,也就是我们需要广播的对象
            if (entries != null) {
                ArrayList receivers = null;
                for (int i=0; i= 0) {
                        if (receivers == null) {
                            receivers = new ArrayList();
                        }
                        receivers.add(receiver);//添加进待广播ReceiverRecord的集合中
                        receiver.broadcasting = true;//广播标志位设置为true
                    } else {
                        //省略部分代码
                    }
                }
                if (receivers != null) {
                    for (int i=0; i

LocalBroadcastManager#Handler

收到消息之后进行消息分发,Handler创建的之后传入的Looper是主线程的,那么我们的回调也就切换到主线程中了

    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);
                }
            }
        };
    }

executePendingBroadcasts

广播的分发,遍历待处理的集合,并调用onReceive进行分发

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

这里面将mPendingBroadcasts可能发生改变看,所以需要同步代码块,集合转换数组,为了提高效率,同步代码块中只对原集合操作保证其安全,并不需要包括广播分发。

sendBroadcastSync

同步分发广播,并不会切换线程,回调的线程是在调用者的线程

public void sendBroadcastSync(Intent intent) {
    if (sendBroadcast(intent)) {
        executePendingBroadcasts();
    }
}

你可能感兴趣的:(LocalBradcastManager源码分析)