2020-04-17-Android本地廣播的實現(xiàn)原理

getInstance

LocalBroadcastManager實現(xiàn)了一個單例模式,每個進程只能獲取到一個實例。

    @NonNull
    public static LocalBroadcastManager getInstance(@NonNull Context context) {
        synchronized (mLock) {
            if (mInstance == null) {
                mInstance = new LocalBroadcastManager(context.getApplicationContext());
            }
            return mInstance;
        }
    }

為了實現(xiàn)單例,構造函數(shù)是私有的。

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

構造函數(shù)傳入了Application Context,并且初始化了一個運行在主線程的Handler對象。

registerReceiver

首先看下LocalBroadcastManager內(nèi)部有兩個HashMap結構分別保存了receiver和action的鍵值對。

    private final HashMap<BroadcastReceiver, ArrayList<ReceiverRecord>> mReceivers
            = new HashMap<>();
    private final HashMap<String, ArrayList<ReceiverRecord>> mActions = new HashMap<>();

注冊廣播接收器的方法跟全局廣播的形式是一樣的,傳入一個receiver跟一個intentFilter。
注釋1 初始化一個ReceiverRecord對象,它是一個內(nèi)部靜態(tài)類,保存了對應的receiver和intentFilter;
注釋2 將ReceiverRecord對象加入到ArrayList列表中,因為同一個receiver可能被注冊多次,有多個intentFilter;
注釋3 將每個action對應的ReceiverRecord對象加入到列表中,同樣的,同一個action可能被多個receiver監(jiān)聽。

    public void registerReceiver(@NonNull BroadcastReceiver receiver,
            @NonNull IntentFilter filter) {
        synchronized (mReceivers) {
            ReceiverRecord entry = new ReceiverRecord(filter, receiver);//1
            ArrayList<ReceiverRecord> filters = mReceivers.get(receiver);
            if (filters == null) {
                filters = new ArrayList<>(1);
                mReceivers.put(receiver, filters);
            }
            filters.add(entry);//2
            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);//3
                }
                entries.add(entry);
            }
        }
    }

sendBroadcast

發(fā)送廣播的時候需要去找到對應監(jiān)聽的receiver,對廣播進行分發(fā)。因為本地廣播是進程內(nèi)共享的,可能出現(xiàn)競爭關系,這里使用了synchronized進行同步操作。
注釋1 從mActions中找到這個廣播的action對應的列表;
注釋2 遍歷列表找到對應的receiver;
注釋3 根據(jù)IntentFilter的匹配規(guī)則進行匹配;
注釋4 將匹配成功的receiver加入到列表,并且將broadcasting標志置為true;
注釋5 處理完成后將broadcasting標志復位;
注釋6 將所有匹配到的receiver封裝成BroadcastRecord對象加入到mPendingBroadcasts列表中;
注釋7 通過handler消息對廣播進行分發(fā)處理。

    public boolean sendBroadcast(@NonNull 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());//1
            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);//2
                    if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);

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

                    int match = receiver.filter.match(action, type, scheme, data,
                            categories, "LocalBroadcastManager");//3
                    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;//4
                    } 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;//5
                    }
                    mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));//6
                    if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                        mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);//7
                    }
                    return true;
                }
            }
        }
        return false;
    }

executePendingBroadcasts

最后看下廣播的分發(fā)過程,注釋1處調(diào)用了接收器的onReceive方法。

    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);
                    if (!rec.dead) {
                        rec.receiver.onReceive(mAppContext, br.intent);//1
                    }
                }
            }
        }
    }

sendBroadcastSync

本地廣播還有一個比較特殊的地方,是可以使用同步方法,保證廣播發(fā)送的時序。
實際上普通發(fā)送廣播的方式,真正分發(fā)的操作是通過handler實現(xiàn)的一個異步過程。
而sendBroadcastSync方法是直接調(diào)用executePendingBroadcasts方法,可能會阻塞等待操作實行完成。

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

參考

Android本地廣播和全局廣播的區(qū)別及實現(xiàn)原理

?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容