动态注册:
1、在需要发送广播的activity中写入:
、 Intent intent = new Intent();
intent.setAction("myAction"); //自定义action,接收广播时必须一样
intent.putExtra("code",resp.errCode); // 需要传递的信息;
sendBroadcast(intent); //发送广播
2、在需要 接收广播的activity中写入:
private myReceive mReceive=new myReceive();
IntentFilter filter = new IntentFilter("myAction"); //过滤器,相当于收音机的频道
if(mReceive==null) { mReceive=new myReceive(); } //防止出现多个广播接收器,接收多次信息 **
registerReceiver(mReceive, intentFilter); //注册广播
public class myReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction(); //获取动作,通过这个标志判断是否是这个广播
int code=intent.getIntExtra("code", 1024); //获取的广播信息
try {
if(action.equals("myAction")){
//进行关于广播的操作
} catch (Exception e) {
// TODO: handle exception
}
}
}
官方推荐反注册在onDestory()中
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mr);
}