1 本次广播都是自定义的广播,自己发送,自己接收。
2 本次广播只在本应用程序内部有效,不会传递到其他应用程序中,这也保证了安全性。
3 本地广播只能采用动态注册的方法注册
4 只能发送标准广播,不能发送有序广播
5 本地广播和其他广播在写法上唯一不同的地方就是发送和接收都要通过LocalBroadcastManager的对象来进行
注册广播
创建类
public class FirstReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
注册
private LocalBroadcastManager localBroadcastManager;
private FirstReceiver receiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_activity_layout);
//首先获取LocalBroadcastManager对象
localBroadcastManager=LocalBroadcastManager.getInstance(this);
receiver=new FirstReceiver();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("zyl");
//注册广播
localBroadcastManager.registerReceiver(receiver,intentFilter);
)
取消注册
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(receiver);
}
发送广播
private LocalBroadcastManager localBroadcastManager
localBroadcastManager=LocalBroadcastManager.getInstance(this);
Intent intent=new Intent();
intent.setAction("zyl");
localBroadcastManager.sendBroadcast(intent);
网友评论