Android Broadcast mechanism

Source: Internet
Author: User

1. Broadcast Recipient

The broadcast receiver simply means the Java class that receives the broadcast intent, which inherits the Broadcastreceiver class and overrides the OnReceive method

public void OnReceive (Context context,intent Intent),

Where intent can get the data passed

The three broadcast receivers are defined as follows:

Priority Level ReceiverSelf3 > ReceiverSelf2 > ReceiverSelf1 (visible in registered code)

public class ReceiverSelf1 extends Broadcastreceiver {
Private final String TAG = "ReceiverSelf1";
@Override
public void OnReceive (context context, Intent Intent) {
String name = Intent.getextras (). getString ("name");
if (Isorderedbroadcast ()) {
LOG.D (TAG, "OnReceive: Getextras in ordered broadcast" +name);
}else{
LOG.D (TAG, "OnReceive: Getextras in unordered broadcast" +name);
}
When you send an ordered broadcast, you can let the broadcast no longer pass down. RECEIVERSELF2 cannot receive broadcasts (higher priority for RECEIVERSELF1 in manifest)
If you send an unordered broadcast, it crashes.
}
}
public class ReceiverSelf2 extends Broadcastreceiver {
Private final String TAG = "RECEIVERSELF2";
@Override
public void OnReceive (context context, Intent Intent) {
String name = Intent.getextras (). getString ("name");
if (Isorderedbroadcast ()) {
LOG.D (TAG, "Onreceive:getextras in orderly broadcast" +name);
}else{
LOG.D (TAG, "Onreceive:getextras in unordered broadcast" +name);
}
if (Isorderedbroadcast ()) {//Determines whether an ordered broadcast is accepted
Bundle bundle = Getresultextras (false);
if (bundle! = null) {
String orderData = bundle.getstring (Broadcastactivity.order_data);
LOG.D (TAG, broadcastactivity.order_data+ "" +orderdata);
}

String resultdata = Getresultdata ();
LOG.D (TAG, broadcastactivity.order_data+ "" +resultdata);
Setresultdata ("Data with a priority of 3 setresultdata"); Modify the data for an ordered broadcast
LOG.D (TAG, "OnReceive: _______________________________________________");
Abortbroadcast (); Radio no longer spreads down
}
}
public class ReceiverSelf3 extends Broadcastreceiver {
Private final String TAG = "ReceiverSelf3";
@Override
public void OnReceive (context context, Intent Intent) {
String name = Intent.getextras (). getString ("name");
if (Isorderedbroadcast ()) {
LOG.D (TAG, "Onreceive:getextras in orderly broadcast" +name);
}else{
LOG.D (TAG, "Onreceive:getextras in unordered broadcast" +name);
}

if (Isorderedbroadcast ()) {//Determines whether an ordered broadcast is accepted
Bundle bundle = Getresultextras (false);
if (bundle! = null) {
String orderData = bundle.getstring (Broadcastactivity.order_data);
LOG.D (TAG, broadcastactivity.order_data+ "" +orderdata);
}

String resultdata = Getresultdata ();
LOG.D (TAG, broadcastactivity.order_data+ "" +resultdata);
Setresultdata ("Data with a priority of 3 setresultdata"); Modify the data for an ordered broadcast
LOG.D (TAG, "OnReceive: _______________________________________________");
}
}

The broadcast of Broadcastreceiver is divided into two categories: disordered broadcasting and orderly broadcasting.

2. Registered Broadcast

There are two ways to register a broadcast, one for static registration, that is to register a broadcast recipient in Androidmanifest. Another way to register dynamically is through code registration.

<receiver android:name= ". Androidbroadcast.receiverself1 ">
<intent-filter android:priority= "1" >
<action android:name= "Com.xiazdong"/>
</intent-filter>
</receiver>

<receiver android:name= ". Androidbroadcast.receiverself2 ">
<intent-filter android:priority= "2" >
<action android:name= "Com.xiazdong"/>
</intent-filter>
</receiver>

<receiver android:name= ". Androidbroadcast.receiverself3 ">
<intent-filter android:priority= "3" >
<action android:name= "Com.xiazdong"/>
</intent-filter>
</receiver>

Note: Priority indicates that the recipient is -1000~1000, and the receiver with the higher priority receives the broadcast first.

Intent-filter define your own intention to receive broadcasts (can be filtered)


Dynamic registration is as follows: In code by invoking the Registerreceiver () method of the context for dynamic registration Broadcastreceiver, the code is as follows:

@Override protected void Onresume () { super.onresume (); Instantiate Broadcastreceiver Subclass & intentfilter mbroadcastreceiver mbroadcastreceiver = new Mbroadcastreceiver ( ); Intentfilter intentfilter = new Intentfilter (); Set the type of receive broadcast intentfilter.addaction (Android.net.conn.CONNECTIVITY_CHANGE); Call the context's Registerreceiver () method for dynamic registration registerreceiver (Mbroadcastreceiver, intentfilter);} After registering the broadcast, to remember to destroy the broadcast in the appropriate location//in OnPause () unregisterreceiver (mbroadcastreceiver)//When this activity is instantiated, The Mybroadcastreceiver is dynamically registered to the system//When this activity is destroyed, dynamically registered Mybroadcastreceiver will no longer receive the corresponding broadcast. @Override protected void OnPause () { super.onpause (); Destroy the broadcast Unregisterreceiver (Mbroadcastreceiver) in the Onresume () method ; }}

Note:

    • Dynamic broadcasts are best written off in the activity's Onresume () registration, OnPause ().
    • For dynamic broadcasts, there is a need to sign out of registration, otherwise it will lead to memory leaks, duplicate registration, repeated logoff is not allowed

More questions about broadcast registration follow the last article in the Reference blog post.

3. Disorderly Broadcasting

Out-of-order broadcasts are the broadcasts we often use, primarily through the public abstract void Sendbroadcast (Intent Intent) method and passing data through Intent. The code examples are as follows:

Intent Intent = new Intent ();
Intent.setaction ("Com.xiazdong");
Intent.putextra ("name", "Xiazdong");
Send an unordered broadcast
This.sendbroadcast (Intent);
Toast.maketext (Getapplicationcontext (), "Send broadcast Success", Toast.length_short). Show ();

Out-of-order broadcasts are received by the corresponding interested (Intent-filter matches ) that are registered by Androidmainfest and are unordered (if priority is set, the Broadcastreceiver with high precedence is received first). If there is a corresponding permission requirement to send the broadcast, broadcastreceiver must have the appropriate permissions if you want to receive this broadcast.

Out-of-order broadcasts can not be intercepted, cannot be terminated, cannot be modified, and any recipient of the unordered broadcast can be received as long as the matching criteria are available. If you want to pass data through an unordered broadcast, you can call the Intent.putextra method pass, and the receiver can pass intent.get ... Receive, not receive through Getresultdata.

4. Orderly Broadcasting

An ordered broadcast can be sent in the following two ways:

public abstract void Sendorderedbroadcast (Intent Intent, String receiverpermission, Broadcastreceiver resultreceiver, Handler Scheduler, int initialcode, String initialdata, Bundle Initialextras)

public void Sendorderedbroadcast (Intent Intent,

The following describes the meaning of each of the following parameters:

Intent: matching rules for all broadcast receivers

receiverpermission: Specify permissions for the broadcast receiver, general customization, infrequently used, and can be passed null

Resultreceiver: Specifies a final broadcast receiver, equivalent to the finally function, regardless of the priority, the last to receive a broadcast (), This time the received broadcast is out of order (can be verified in Broadcastreceiver by the Boolean orderedbroadcast = Isorderedbroadcast () method), But the data can be obtained by means of Getresultdata, which is the special case mentioned above. Even if the previous broadcast calls Abortbroadcast (), the receiver can still receive an unordered broadcast.


Scheduler: look at English not how to understand what meaning, generally passed null.
initialcode: Specify a code, general pass ACTIVITY.RESULT_OK.
initialdata: Passes a string of data. The corresponding data is obtained through string resultdata = Getresultdata () in Broadcastreceiver, and the data is modified by Setresultdata ("Setresultdata Data with Priority 3"). The data is passed to the next lower priority broadcastreceiver, and if the data is not modified using setresultdata in the higher priority broadcastreceiver, the lower-priority received data is the most primitive data. That is, the value of Initialdata.
Initialextras: Pass a Bundle object, that is, you can pass multiple types of data. Corresponding in the broadcastreceiver through bundle bundle = Getresultextras (false) to obtain the bundle object, and then through the bundle of various get methods to obtain data ; Pass in a modified bundle through Setresultextras (), passing the bundle object to the next lower-priority broadcastreceiver If you do not use Setresultextras to modify data in a higher priority broadcastreceiver, the received data with lower priority is still the most primitive bundle object, that is, the value of Initialextras.
Send an unordered broadcast as follows:
 
     
    
Intent Intent = new Intent ();
Intent.setaction ("Com.xiazdong");
Intent.putextra ("name", "Xiazdong");
Send an ordered broadcast
This.sendorderedbroadcast (Intent,null);
Passing data through bundles
Bundle bundle = new bundle ();
Bundle.putstring (Order_data, "orderly broadcasts pass data through bundles");
Sendorderedbroadcast (Intent,null,null,mhandler, ACTIVITY.RESULT_OK, "Send an orderly broadcast", bundle);
Toast.maketext (Getapplicationcontext (), "Send broadcast Success", Toast.length_short). Show ();

Run the following log:
       
5. Receive lock screen and unlocking event via broadcast
Android developers can register the receiver, monitor the phone's lock screen and unlocking events, and customize the receiver as follows:
 Private classScreenbroadcastreceiverextendsBroadcastreceiver {PrivateString action =NULL; @Override Public voidOnReceive (context context, Intent Intent) {action = Intent.getaction ();if(Intent.ACTION_SCREEN_ON.equals (ACTION)) {//Open screenMlistener.onscreenon (); LOG.D (TAG, "onreceive:"+"Open Screen"); }Else if(Intent.ACTION_SCREEN_OFF.equals (ACTION)) {//Lock screenMlistener.onscreenoff (); LOG.D (TAG, "onreceive:"+"Lock Screen"); }        }    }
While registering the broadcast through this dynamic registration, the receiver value is set through Intentfilter to receive the lock screen and the unlocking event without concern for other events:
New Intentfilter (); filter.addaction (intent.action_screen_on); filter.addaction (Intent.action_screen_off); Mcontext.registerreceiver (mscreenreceiver, filter);
This way, the OnReceive callback is called when the lock screen and the unlocking event occur.

Reference:
http://www.jianshu.com/p/0b3a7b35d76d
http://blog.csdn.net/xiazdong/article/details/7768807/
Http://www.jianshu.com/p/ca3d87a4cdf3





Android Broadcast 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.