阅读 807

好用的假广播 LocalBroadcastManager

简介

从名字来看,这货就是个广播管理类,其实不然,它套用了广播的空壳,却实现了线程间通信;远看是广播,近看是线程间通信;

说它好用,是因为它短小,精悍,而且是系统自带,满足大部分常规要求;如果你用EventBus确实使用方式更简单,但是apk体积包增加,方法数增加,同样处理方法调用栈增加,是不是性能成本也相应的增加,虽然单独来看成本微不足道,但也是增加了啊

其使用方式也和广播一样;让我们看看源码

源码分析

其相关的有两个内部类: ReceiverRecord、BroadcastRecord;先从软柿子开始

接收者信息 ReceiverRecord

        final IntentFilter filter;
        final BroadcastReceiver receiver;
        boolean broadcasting;
        boolean dead;
复制代码

有以下信息:

  1. 消息处理对象
  2. 可处理消息对象
  3. 辅助是否添加到处理集合(详情见发送消息代码)
  4. 是否可以处理相关事件(详情看,解注、消息处理流程)

消息所有信息 BroadcastRecord

        final Intent intent;
        final ArrayList<ReceiverRecord> receivers;
复制代码

包括了消息intent、需要处理此消息的接收者信息集合

LocalBroadcastManager 构造器以及成员变量

private final Context mAppContext;

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

    private final ArrayList<BroadcastRecord> mPendingBroadcasts = new ArrayList<>();

    static final int MSG_EXEC_PENDING_BROADCASTS = 1;

    private final Handler mHandler;

    private static final Object mLock = new Object();
    private static LocalBroadcastManager mInstance;

    @NonNull
    public static LocalBroadcastManager getInstance(@NonNull 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);
                }
            }
        };
    }
复制代码
  1. 采用了单例模式
  2. 使用handler进行通信
  3. 以广播接收者为key, 以广播接收者信息作为value存储所有的 广播接收者信息;来进行快速存储、取消接收者信息
  4. 以广播动作为key,以广播接收者信息作为value存储所有的 广播接收者信息,快速定位消息处理者集合
  5. 消息处理信息集合

为什么有两个集合呢? 查找消息可能处理者时,mActions比较快速;mReceivers,由于锁的重入性,删除时,避免当前线程其它的action处理,也就是保证虽然解注,但仍然有可能在处理者信息集合中,通过这种方式快速阻止继续执行(通过dead参数)

不过我个人任务还是有点勉强说通,也有可能有其它原因

注册信息接收

public void registerReceiver(@NonNull BroadcastReceiver receiver,
            @NonNull 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);
            }
        }
    }
复制代码

mActions、mReceivers添加注册者信息

解注消息接收

public void unregisterReceiver(@NonNull BroadcastReceiver receiver) {
        synchronized (mReceivers) {
            final ArrayList<ReceiverRecord> filters = mReceivers.remove(receiver);
            if (filters == null) {
                return;
            }
            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);
                        }
                    }
                }
            }
        }
    }
复制代码

mActions、mReceivers删除信息;同时删除空数据集合

消息处理

    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);
                    }
                }
            }
        }
    }
复制代码

mPendingBroadcasts 中存储了处理的消息intent、处理者集合;根据处理者解注状态来确定是否需要处理

消息发送

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

                    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");
                    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) {
                    for (int i=0; i<receivers.size(); i++) {
                        receivers.get(i).broadcasting = false;
                    }
                    mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                    if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                        mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                    }
                    return true;
                }
            }
        }
        return false;
    }
复制代码

异步处理,利用Handler发送消息,在主线程中处理;代码流程:

  1. 通过intent的action查找可能的处理者
  2. 通过intent的其它信息,确定需要处理的处理者信息,并且避免重复(broadcasting添加后为true,未添加为false)
  3. mPendingBroadcasts 中加入消息和需要处理者信息集合
  4. 发送消息处理
    public void sendBroadcastSync(@NonNull Intent intent) {
        if (sendBroadcast(intent)) {
            executePendingBroadcasts();
        }
    }
复制代码

发送和处理在同一个线程;虽然发送了消息,但是当前线程立刻就执行了;中间方法调用栈未枷加锁,也就是有极小概率,不能保证同步执行

原理总结

  1. 利用了广播的使用方式,利于开发者使用
  2. 利用Intent可以在进程间传递,而用做消息
  3. 使用Handler机制,使消息可以在主线程回调处理
  4. 使用synchronized 进行同步
  5. 使用了单例模式,保证同一个类加载器内唯一
  6. 同步执行消息调用,并不一定能保证同步

整体来说利用了广播使用方式,和类的一些实现,外加Handler来实现线程间通信

技术变化都很快,但基础技术、理论知识永远都是那些;作者希望在余后的生活中,对常用技术点进行基础知识分享;如果你觉得文章写的不错,请给与关注和点赞;如果文章存在错误,也请多多指教!