本地广播很好的解决了全局广播的安全问题
在使用本地广播的时候也比较简单,只需要定义一个类就可以了,获取实例并不是new对象,而是从他内部提供的方法中获取实例,代码如下
代码也不是很难,和动态注册广播差不多,只是在进行相应的注册 解注册的时候都是使用LocalBroadcastManager的实例来操作
public class Main3Activity extends AppCompatActivity {
private Intent mIntent;
private Button mBtnSend;
private MyLocalReceiver mMyLocalReceiver;
private LocalBroadcastManager mLocalBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
mLocalBroadcastManager=LocalBroadcastManager.getInstance(this);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("chuang.meng");
mMyLocalReceiver=new MyLocalReceiver();
mLocalBroadcastManager.registerReceiver(mMyLocalReceiver,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocalBroadcastManager.unregisterReceiver(mMyLocalReceiver);
}
public void button1(View view) {
Intent intent=new Intent("chuang.meng");
mLocalBroadcastManager.sendBroadcast(intent);
}
class MyLocalReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast toast=Toast.makeText(context, "MyLocalReceiver is receiver",Toast.LENGTH_SHORT);
toast .setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
}