First, the broadcast through the intent sent out
// Define a broadcast intent filter Private String action = "Com.xxx.demo.Broadcast.STATUS_CHANGED"; // Send broadcast New Intent (); Intent.setaction (action); Servicesimulation. this. Sendbroadcast (intent);
Second, define the Broadcasereceiver class that receives the broadcast
1, inherit from Android.content.BroadcastReceiver;
2, must implement its OnReceive method, and in which all the actions triggered;
Public class extends broadcastreceiver{ /** * This object is created when a broadcast is received and executes the OnReceive method, * Once the OnReceive method is executed (return), the object is destroyed (after the burn mechanism is read). * The next time the broadcast is received, the object will be recreated again, and then the burn mechanism is executed again. */ @Override publicvoid onreceive (context context, Intent Intent) { // TODO do someing ... }}
3, must register;
(1) Registration in Androidmanifest.xml (static registration):
<ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <receiverAndroid:name=". Servicebroadcastreceiver "> <Intent-filter> <ActionAndroid:name= "Com.xxx.demo.Broadcast.STATUS_CHANGED"/> </Intent-filter> </receiver> <!--exported receiver does not require permission - </Application>
Note: You must make sure that the <action> Android:name property is a globally unique string!
(2) Register in code (dynamic registration):
1. Declaring a broadcast receiver
// registering a servicesimulation broadcast receiver servicebroadcastreceiver Receiver;
// Status_changed is a channel for servicesimulation to send broadcasts. Private Final Static String status_changed = "Com.xxx.demo.Broadcast.STATUS_CHANGED";
2, create Intentfilter object;
3, call Context.registerreceiver () method registration;
/*** Register Servicesimulation's broadcast receiver*/ Private voidRegisterservicebroadcastreceiver () {//instantiate the broadcast sink object receiver, which is a class member variableReceiver =NewServicebroadcastreceiver (); //Create an intent filter objectIntentfilter filter =NewIntentfilter (); //set the action for the intent filter object, that is: Broadcast channelfilter.addaction (status_changed); //Register the broadcast receiverMainactivity. This. Registerreceiver (receiver, filter); }
3. Call the Context.unregisterreceiver () method to log off.
/** * Unregister Servicesimulation's broadcast receiver */ privatevoid Unregisterservicebroadcastreceiver () { // logoff broadcast sink object receiver, the object is a class member variable Mainactivity. This . Unregisterreceiver (receiver); }
Iii. contents of the broadcast
When calling Context.sendbroadcast (intent) to send a broadcast, the data can be transmitted by wrapping the specific broadcast content in the parameter intent.
The broadcast mechanism in Android framework