广播接收器BroadcastReceiver
用于接收App传递过来的信息
新建-other-broadcastreceiver
MainAty:
常规性事件接听器代码
case R.id.btnSendMsg:
// Intent i=new Intent(this,MyReceiver.class);
//注册接收器后就不能使用显式intent,需使用下面的隐式方法,无注册的话使用上面代码即可
Intent i=new Intent(MyReceiver.ACTION);
i.putExtra("data","HEE");
//sendBroadcast(i);
//如果有优先级广播,则使用下面,不然则上述即可
sendOrderedBroadcast(i,null);
break;
case R.id.btnReg://注册
if (receiver==null){
receiver=new MyReceiver();
registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));
}
break;
case R.id.btnUnreg://注销
if(receiver!=null){
unregisterReceiver(receiver);
receiver=null;
}
break;
}
}
private MyReceiver receiver=null;
Myreceiver:
public void onReceive(Context context, Intent intent) {
System.out.println("接收到了消息,消息的内容是:"+intent.getStringExtra("data"));
abortBroadcast();//让优先级低的receiver不会收到广播
}
}