前言
本地广播只能在应用程序内部进行传递,并且只能通过动态注册.这种本地广播的好处是不会将一些隐蔽信息被全局广播出去.
使用说明
创建广播接受类,继承BroadcastReceiver
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (TextUtils.equals(intent.getAction(), DEMO_ACTION)){ Toast.makeText(context, "触发本地广播", Toast.LENGTH_SHORT).show(); } } }
注册广播,请注意,注册本地广播需要使用LocalBroadcastManager进行注册,这点与静态广播不通.
private CloseDialogReceiver mCloseDialogReceiver; private void registerReceiver(){ mCloseDialogReceiver = new CloseDialogReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(DEMO_ACTION); LocalBroadcastManager.getInstance(this).registerReceiver(mCloseDialogReceiver, intentFilter); }
发送广播,发送也需要使用LocalBroadcastManager发送
public void send(){ Intent dismissDialog = new Intent(DEMO_ACTION); LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this); localBroadcastManager.sendBroadcast(dismissDialog); }
注销广播
LocalBroadcastManager.getInstance(this).unregisterReceiver(mCloseDialogReceiver);