Android_broadcastreceiver Broadcasting mechanism

Source: Internet
Author: User

The broadcast receiver (Broadcastreceiver), as its name implies, is used to receive broadcasts from systems and applications. It is used to receive broadcast Intent, and broadcast Intent is sent by calling Context.sendbroadcast (), Context.sendorderedbroadcast (). Typically a broadcast Intent can be received by multiple broadcast receivers subscribed to this Intent. For example, when the system will generate a broadcast after the boot, receive this broadcast can realize the function of start-up service, when the network status changes, the system will generate a broadcast, receive this broadcast can prompt and save data and other operations; When the battery level changes, the system generates a broadcast, Receiving this broadcast will be able to inform the user of the timely saving progress when the battery is low.
1, create Broadcastreceiver object, need to inherit android.content.BroadcastReceiver, and implement its OnReceive method.
public class Myreceiver extends Broadcastreceiver {private static final String TAG = "Myreceiver"; @Overridepublic void OnR Eceive (Context arg0, Intent Intent) {String msg = Intent.getstringextra ("msg"); LOG.I (TAG, MSG);}}
Within the OnReceive method, the data in the intent that comes with the broadcast can be obtained and processed.
2, after the creation of Broadcastreceiver, it is also necessary to register.
- Static Registration: Configuring in the Androidmanifest.xml file
    <receiver android:name= ". Myreceiver ">        <intent-filter>            <action android:name=" Android.intent.action.MY_BROADCAST "/>        </intent-filter>    </receiver>
After the configuration, as long as the Android.intent.action.MY_BROADCAST address of the broadcast, Myreceiver can receive. Note that this method of registration is permanent, that is, when the application is closed, if there is broadcast information, Myreceiver will also be called by the system automatically run.
- Dynamic Registration: Specify the broadcast address dynamically in the code and register it, usually by registering a broadcast in activity or service.
Class Broadcastreceiverlistener implements Onclicklistener{public void OnClick (View arg0) {//Dynamic Registration// Generates a Broadcastreceiver object myreceiver = new Myreceiver ();//generates a Intentfilter object intentfilter filter = new Intentfilter ();// Add a actionfilter.addaction ("Android.intent.action.MY_BROADCAST") for intentfilter;// Register the Broadcastreceiver object in the system Registerreceiver (myreceiver, filter);}}
Registerreceiver is a method in the Android.content.ContextWrapper class where activity and service inherit contextwrapper, so they can be called directly. In the actual application, we register a broadcastreceiver in activity or service, when the activity or service is destroyed if not de-registration, the system will report an exception, indicating whether we forgot to release the registration. So, remember to perform the de-registration operation in a specific place:
@Override  protected void OnDestroy () {      Super.ondestroy ();      Unregisterreceiver (Myreceiver);  
Executing this line of code will solve the problem. Note that this registration is in contrast to static registration, which is not resident, which means that the broadcast follows the program's life cycle.
3, after registering good broadcastreceiver, you can use it.
Class Broadcastreceiverlistener implements Onclicklistener{public void OnClick (View v) {Intent Intent = new Intent ("Andro Id.intent.action.MY_BROADCAST "); Intent.putextra (" msg "," Hello world! "); /intent.setaction ("Android.intent.action.MY_BROADCAST"); Sendbroadcast (intent);}}
Sendbroadcast is also a method in the Android.content.ContextWrapper class that sends a intent object of the specified address and parameter information as a broadcast.

Click on the button, you can send out the broadcast, and received by Myreceiver.

>>> The above example is just a receiver to receive the broadcast, if more than one recipient has registered the same broadcast address, what will be the situation, can receive the same broadcast at the same time, there will be interference between each other? This involves the concept of general broadcasting and orderly broadcasting.

General Broadcast (normal broadcast)
Ordinary broadcasts are completely asynchronous for multiple receivers, and usually each recipient does not have to wait for the broadcast to be received, and the recipient has no effect on each other. For this broadcast, the receiver cannot stop the broadcast, that is, the receiving action of the other receivers cannot be blocked.
Create a new three Broadcastreceiver,firstreceiver, Secondreceiver, and thirdreceiver to demonstrate this process.
public class Firstreceiver extends Broadcastreceiver {            private static final String TAG = "Normalbroadcast";            @Override public      void OnReceive (context context, Intent Intent) {          String msg = Intent.getstringextra ("msg");          LOG.I (TAG, "Firstreceiver:" + msg);}      }
public class Secondreceiver extends Broadcastreceiver {            private static final String TAG = "Normalbroadcast";            @Override public      void OnReceive (context context, Intent Intent) {          String msg = Intent.getstringextra ("msg");          LOG.I (TAG, "Secondreceiver:" + msg);      
public class Thirdreceiver extends Broadcastreceiver {            private static final String TAG = "Normalbroadcast";            @Override public      void OnReceive (context context, Intent Intent) {          String msg = Intent.getstringextra ("msg"); C10/>LOG.I (TAG, "Thirdreceiver:" + msg);}      }  
Click the Send button again to send a broadcast, console print:

Three receivers receive this broadcast and attempt to terminate the broadcast if the code is added to the last line of the OnReceive method of the three recipients:
Abortbroadcast ();

Click the Send button again, the three recipients in the console still print their own logs, indicating that the receiver cannot terminate the broadcast.

Orderly broadcast (Ordered broadcast)
Ordered broadcast is special, it is sent only to the higher priority recipients, and then by the higher priority recipients to the lower priority recipients, high priority recipients have the ability to terminate the broadcast.
Or use three broadcastreceiver to give an example.

public class Firstreceiver extends Broadcastreceiver {            private static final String TAG = "Orderedbroadcast";          @Override public    void OnReceive (context context, Intent Intent) {        String msg = Intent.getstringextra ("msg");        LOG.I (TAG, "Firstreceiver:" + msg);                Bundle bundle = new bundle ();        Bundle.putstring ("msg", MSG + "@FirstReceiver");        Setresultextras (bundle);    
public            Class Secondreceiver extends Broadcastreceiver {private static final String TAG = "Orderedbroadcast"; @Override public void OnReceive (context context, Intent Intent) {String msg = Getresultextras (true). Get          String ("msg");                    LOG.I (TAG, "Secondreceiver:" + msg);          Bundle bundle = new bundle ();          Bundle.putstring ("msg", MSG + "@SecondReceiver");      Setresultextras (bundle); }}
public class Thirdreceiver extends Broadcastreceiver {            private static final String TAG = "Orderedbroadcast";            @Override public      void OnReceive (context context, Intent Intent) {          String msg = Getresultextras (True). GetString ( "MSG");          LOG.I (TAG, "Thirdreceiver:" + msg);}      }
In both Firstreceiver and Secondreceiver, the Setresultextras method was used to set a bundle object as the result set object, which was passed to the next recipient, so that Recipients with low priority can use Getresultextras to obtain the latest processed collection of information.
Then we need to register a broadcast address for three recipients, and we'll modify the Androidmainfest.xml file:
< Receiver Android:name= ". Firstreceiver "> <intent-filter android:priority=" "> <action android:name=" android.intent.act Ion.  My_broadcast "/> <category android:name=" Android.intent.category.DEFAULT "/> </intent-filter> </receiver> <receiver android:name= ". Secondreceiver "> <intent-filter android:priority=" 999 "> <action android:name=" android.intent.act Ion.  My_broadcast "/> <category android:name=" Android.intent.category.DEFAULT "/> </intent-filter> </receiver> <receiver android:name= ". Thirdreceiver "> <intent-filter android:priority=" 998 "> <action android:name=" android.intent.acti On.  My_broadcast "/> <category android:name=" Android.intent.category.DEFAULT "/> </intent-filter> </receiver> 
Now the <intent-filter> of these three receivers has a android:priority attribute and decreases in turn. This property has a range of 1000 to 1000, and the higher the value, the greater the precedence.
Then modify the code that sends the broadcast:
Class Broadcastreceiverlistener implements Onclicklistener{public void OnClick (View arg0) {Intent Intent = new Intent ("an Droid.intent.action.MY_BROADCAST "); Intent.putextra (" msg "," Hello world! "); /intent.setaction ("Android.intent.action.MY_BROADCAST");//Sendbroadcast (intent); Sendorderedbroadcast (Intent, " Scott.permission.MY_BROADCAST_PERMISSION ");}}
When sending an ordered broadcast using the Sendorderedbroadcast method, a permission parameter is required, and if NULL indicates that the recipient is not required to declare the specified permission, and if it is not NULL, the recipient is required to declare the specified permission to receive the broadcast. This is done from a security perspective, such as the system's text message is the form of orderly broadcast, an application may be the ability to intercept spam messages, when the message arrives it can first receive the text message broadcast, if necessary, stop the broadcast transmission, such software must declare the permission to receive text messages.
So define a permission in Androidmainfest.xml:
<permission android:protectionlevel= "Normal" android:name= "Scott.permission.MY_BROADCAST_PERMISSION"/>  
It then declares that this permission was used:
<uses-permission android:name= "Scott.permission.MY_BROADCAST_PERMISSION"/>  
Then we click the Send button to send a broadcast, and the console prints as follows:

We see that the receive is in order, and the first and the second both add their own tags to the result set and pass to the lower-priority recipients.

Since it is sequential delivery, try to terminate this pass, see how the effect, we modify the Firstreceiver code, in the last line of onreceive add abortbroadcast (); Run the program again, this time, only the first receiver executed, the other two failed to execute, because the broadcast was terminated by the first receiver.

Reference:
http://blog.csdn.net/liuhe688/article/details/6955668

Android claims and usage rights http://blog.csdn.net/liuhe688/article/details/641798 3


Android_broadcastreceiver Broadcasting mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.