使用 LocalBroadcastManager

LocalBroadcastManager 用于在应用程序中发送广播意图 ,而不会将它们暴露给不需要的侦听器。

使用 LocalBroadcastManager 比直接使用 context.sendBroadcast() 更有效,更安全,因为你不必担心其他应用程序伪造的任何广播,这可能会造成安全隐患。

以下是发送和接收本地广播的简单示例:

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("Some Action")) {
            //Do something
        }
    }
});

LocalBroadcastManager manager = LocalBroadcastManager.getInstance(mContext);
manager.registerReceiver(receiver, new IntentFilter("Some Action"));

// onReceive() will be called as a result of this call:
manager.sendBroadcast(new Intent("Some Action"));//See also sendBroadcastSync

//Remember to unregister the receiver when you are done with it:
manager.unregisterReceiver(receiver);