LocalBroadcastManager源码分析

一、LocalBroadcastManager是什么

LocalBroadcastManager是Android Support包提供了一个工具,用于在同一个应用内的不同组件间发送Broadcast。LocalBroadcastManager也称为局部通知管理器,这种通知的好处是安全性高,效率也高,适合局部通信,可以用来代替Handler更新UI。

二、LocalBroadcastManager的优点

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

三、LocalBroadcastManager使用

  • 获取LocalBroadcastManager实例
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(ctx);
  • 注册,需要传入BroadcastReceiver和IntentFilter对象
localBroadcastManager.registerReceiver(receiver, filter);
  • 发送,需传入一个Intenet对象
localBroadcastManager.sendBroadcast(intent);
  • 注销,需要通过创建的BroadcastReceiver对象来实现注销
localBroadcastManager.unregisterReceiver(receiver);

四、LocalBroadcastManager使用小例子

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/local_textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="LocalBroadcastReciver"
        android:textColor="@android:color/holo_orange_light"
        android:textSize="20sp" />
</LinearLayout>
public class LocalBroadcastReciverAct extends AppCompatActivity {

    private LocalBroadcastManager localBroadcastManager = null;
    private BroadcastReceiver broadcastReceiver = null;
    private IntentFilter intentFilter = null;

    private static final String ACTION = "LOCAL_BROADCAST_RECIVER_ACTION";
    private TextView localTextview = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_broadcast_reciver);
        localTextview = findViewById(R.id.local_textview);
        localTextview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                localBroadcastManager.sendBroadcast(new Intent(ACTION));
            }
        });
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        initReciverFilter();
        localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
    }

    private void initReciverFilter() {
        broadcastReceiver = new MyBroadcastReciver();
        intentFilter = new IntentFilter(ACTION);
    }

    @Override
    protected void onStop() {
        super.onStop();
        localBroadcastManager.unregisterReceiver(broadcastReceiver);
    }

    private class MyBroadcastReciver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            localTextview.setText("已接受到LocalBroadcastReciver");
        }
    }

}
效果图

五、源码分析

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(ctx);

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

从构造方法私有化,很明显这是一个单利模式,并且进行了加锁操作所以是一个线程安全的单利模式;并且在LocalBroadcastManager的构造方法中我们看见了mHandler = new Handler(context.getMainLooper()),所以可以初步断定LocalBroadcastManager是通过handler+message实现的消息广播,context.getMainLooper()是主线程的Looper,所以这个handler是运行在主线程的,不能进行耗时操作!

localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);

// 广播接收器作为key,接收器记录集合作为value
private final HashMap<BroadcastReceiver, ArrayList<ReceiverRecord>> mReceivers = new HashMap<>();
// 筛选动作(类型)作为key,接收器记录集合作为value
private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<>();
    public void registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
        synchronized (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);
            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);
            }
        }
    }

registerReceiver只是做了一些数据的分类保存操作。ReceiverRecord是一个内部类,主要是存储广播接收器BroadcastReceiver筛选器IntentFilter,及广播运行状态。

    private static final class ReceiverRecord {
        final IntentFilter filter; // 筛选器
        final BroadcastReceiver receiver; // 广播接收器
        boolean broadcasting; // 是否处于激活状态
        boolean dead; // 广播是否已经销毁
        ............
    }


private static final String ACTION = "LOCAL_BROADCAST_RECIVER_ACTION";
localBroadcastManager.sendBroadcast(new Intent(ACTION));

public boolean sendBroadcast(Intent intent) {
        // 保证同一时间,只有一个线程在操作
        synchronized (mReceivers) {
            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);
            
            // 获得对象动作(类型)的广播接收器记录集合
            ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
            if (entries != null) {
                if (debug) Log.v(TAG, "Action list: " + entries);
            
                // 真正符合条件的接收器记录集
                ArrayList<ReceiverRecord> receivers = null;
                // 遍历集合,找到符合条件的ReceiverRecord
                for (int i=0; i<entries.size(); i++) {
                    ReceiverRecord receiver = entries.get(i); 
                    if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);
                    
                    // 已经处于激活状态的ReceiverRecord过滤掉(主要避免重复加入)
                    if (receiver.broadcasting) {
                        if (debug) {
                            Log.v(TAG, "  Filter's target already added");
                        }
                        continue;
                    }

                    // 判断本次循环取出的ReceiverRecord,在动作、数据,分类是否匹配
                    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>();
                        }
                        receivers.add(receiver); // 符合条件的加入到receivers中
                        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) {
                    for (int i=0; i<receivers.size(); i++) {
                        receivers.get(i).broadcasting = false;  // 筛选完后,将状态重置
                    }
                    // 重新构造一个BroadcastRecord对象,并添加到待发送状态下的广播列表
                    mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                    // 查看handler在排队执行的消息中是否有MSG_EXEC_PENDING_BROADCASTS类型,
                    // 没有,添加一个MSG_EXEC_PENDING_BROADCASTS类型的消息
                    if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                        mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                    }
                    return true;
                }
            }
        }
        return false;
    }

sendBroadcast()中主要进行的是广播接受器的筛选操作,然后通知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) {
            final BroadcastRecord[] brs; // 使用数组存放,广播接受记录
            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<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);
                    // 不在销毁状态下,调用接收器的onReceive()方法执行
                    if (!rec.dead) {
                        rec.receiver.onReceive(mAppContext, br.intent);
                    }
                }
            }
        }
    }

executePendingBroadcasts()执行接收器的onReceive()方法。

localBroadcastManager.unregisterReceiver(broadcastReceiver);

    public void unregisterReceiver(BroadcastReceiver receiver) {
        synchronized (mReceivers) {
            // 从mReceivers中移除,并返回对应的记录集合
            final ArrayList<ReceiverRecord> filters = mReceivers.remove(receiver);
            if (filters == null) {
                return;
            }
            // 遍历接收器记录集合,并设置dead = true; 避免正在运行的executePendingBroadcasts()执行此接收器的回调
            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);
                        }
                    }
                }
            }
        }
    }

unregisterReceiver()中主要是资源的释放,并将注册的BroadcastReceiver相关信息,从集合中删除,并设置BroadcastReceiver对应的ReceiverRecorddead状态标记为true,避免被执行。

六、总结

LocalBroadcastManager的内部是通过handler来实现广播消息的分发,这样的广播只能在本应用内分发,所以不必担心安全问题,因为别人根本够不到你~~

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,084评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,623评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,450评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,322评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,370评论 6 390
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,274评论 1 300
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,126评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,980评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,414评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,599评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,773评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,470评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,080评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,713评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,852评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,865评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,689评论 2 354

推荐阅读更多精彩内容