使用 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);