1.
2. Code
1. Layout files
<Button Android:id= "@+id/button1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/btn1" > </Button> <Button Android:id= "@+id/button2"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/btn2" > </Button> <Button Android:id= "@+id/button3"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/btn3" > </Button>
Main.xml
Public classFirstactivityextendsActivity { Public Static FinalString my_action = "Iflab.test.MY_ACTION";//Custom ActionMyreceiver receiver;//Myreceiver Object@Override Public voidOnCreate (Bundle savedinstancestate) {//overloaded OnCreate Method Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); Button BTN1= (Button) Findviewbyid (R.id.button1);//Get IDButton btn2 =(Button) Findviewbyid (R.id.button2); Button Btn3=(Button) Findviewbyid (R.id.button3); Btn1.setonclicklistener (NewView.onclicklistener () {//Setting up Listeners@Override Public voidOnClick (View v) {//TODO auto-generated Method StubIntent Intent =NewIntent ();//Intent ObjectIntent.setaction (my_action);//Set ActionIntent.putextra ("message", "Messages from the broadcast!") ");//set up a broadcast messageSendbroadcast (Intent);//Send broadcast } }); Btn2.setonclicklistener (NewView.onclicklistener () {//Setting up Listeners@Override Public voidOnClick (View v) {//TODO auto-generated Method StubIntentfilter filter =NewIntentfilter ("Iflab.test.MY_ACTION"); Receiver=NewMyreceiver (); Registerreceiver (receiver, filter); //registering a broadcast receiver } }); Btn3.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubUnregisterreceiver (receiver);//destroying broadcast receivers } }); } }
firstactivity
public class myreceiver extends broadcastreceiver{@Override Public void onreceive (Context arg0, Intent arg1) {// overloaded OnReceive method // TODO auto-generated Method stub String str; str = "The Received broadcast message is:" +arg1.getstringextra ("message"); // Receive message Toast.maketext (arg0, Str,toast.length_long). Show (); // display
Myreceiver
<receiver android:name= "Myreceiver" > <intent-filter> </intent-filter> </ Receiver>
configuration file
3. Tips
Do not click Destroy broadcast receiver when not registered broadcast receiver will stop running is a small bug it is necessary for users to do some of their own
Android--Simple broadcast receive and send (2)--dynamic registration of broadcast receivers