Android Tour 17 in Android for broadcast use

Source: Internet
Author: User

Broadcasting is a widely used mechanism for transmitting information between applications, and broadcasts in Android are used to listen for system events or application events! Broadcasts in Android include regular broadcasts, ordered broadcasts, and asynchronous broadcasts (sticky broadcasts)!

Broadcast and permanent broadcast and non-resident broadcast, resident broadcast is registered in the XML, when the application is closed, if there is a corresponding broadcast sent over, the broadcast receiver can be activated, non-resident broadcast is registered in code, when the application is closed, the broadcast is canceled, We can register the broadcast in the activity's OnCreate or Onresume method, and then cancel the registration of the broadcast in the Ondestory or OnPause method;

Note: If the broadcast is very resident, you must unregister the broadcast after the application shuts down, otherwise it will throw an exception!!

Sending of ordinary broadcasts

How to send a normal broadcast using:

Sendbroadcast (Intent Intent): Intent table, all the attempts to match the broadcast receive this broadcast message

Sendbroadcast (Intent, String receiverpermission); Intent as above,receiverpermission represents permission, and the broadcast that matches the permission can receive the corresponding broadcast. If it is null, the request is not approved!

First, use sendbroadcast (Intent Intent) to send the broadcast

1) Register very resident broadcasts by code:

Defines two broadcast receivers Broadcastreceiver Receiver1=new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) {System.out.println ("Receiver1 started!");}}; Broadcastreceiver receiver2=new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) { System.out.println ("Receiver2 started!");}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);//Register Broadcast Intentfilter Filter=new Intentfilter (); Filter.addaction ("Com.xin.action.broadcast"); Registerreceiver (receiver1, filter); Registerreceiver (receiver2, filter);} @Overrideprotected void OnPause () {super.onpause ();//de-register broadcast unregisterreceiver (RECEIVER1); Unregisterreceiver ( RECEIVER2);}
Code registration is a very resident broadcast and we need to unregister the broadcast during the activity's corresponding life cycle: Unregisterreceiver

2) registering resident broadcasts through an XML file, at which time the MyBroadcast1 and MyBroadcast2 are two broadcast classes:

public class MyBroadcast1 extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { System.out.println ("MyBroadcast1 started!");}}
public class MyBroadcast2 extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { System.out.println ("MyBroadcast2 started!");}}

In the application in Androidmanifest.xml, add:

        <receiver android:name= ". MyBroadcast1 ">            <intent-filter>                <action android:name=" Com.xin.action.broadcast "/>            </intent-filter>        </receiver>        <receiver android:name= ". MyBroadcast2 ">            <intent-filter>                <action android:name=" Com.xin.action.broadcast "/>            </intent-filter>        </receiver>
The Intentfilter in the code and the Intent-filter in the XML file are the same intent intent, which means that the broadcasts sent by intent (String ActionName) can be received by the broadcast receivers!

3) Broadcast transmission: The broadcast that matches the intent intent will be activated

Intent intent=new Intent ("Com.xin.action.broadcast"); Sendbroadcast (Intent);
The output is: MyBroadcast1 started,mybroadcast2 started!!

Second, use sendbroadcast (intent, String receiverpermission) to send the broadcast

The second parameter, as shown above, refers to a permission that we need to declare in Androidmanifest.xml:

<permission android:name= "com.xin.permission" android:protectionlevel= "normal"/>
There are many properties available for us to choose, we can go to their own to understand;

The permission definition is then required for both the sending broadcaster and the receiving broadcast party:

This permission is used by the sending broadcast party:

<uses-permission android:name= "Com.xin.permission"/>
Send broadcast by method: Sendbroadcast (Intent, "com.xin.permission"), where the second parameter represents the permission we define Name

The receiver declares the broadcast permission:

        <receiver android:name= ". MyBroadcast1 "android:permission=" com.xin.permission ">            <intent-filter>                <action android:name= "Com.xin.action.broadcast"/>            </intent-filter>        </receiver>
In this way, the use of a broadcast with permission is defined, we both the sender and the receiver need to define the permissions, or the message will not be sent over!

Note that through sendbroadcast (intent, "com.xin.permission"), the broadcast that is sent does not necessarily need to be added android:permission in receiver in order to receive, test discovery, This can also be received without adding:

        <receiver android:name= ". MyBroadcast2 ">            <intent-filter>                <action android:name=" Com.xin.action.broadcast "/>            </intent-filter>        </receiver>

Sending of ordered broadcasts

As the name implies, ordered broadcast is the broadcast is sent in sequence, it according to the definition of priority level of android:priority to carry out an orderly send, a accept to the next receive, the higher the priority, indicating that it received high broadcast level,Android: The priority range is generally between 1000 and 1000;
The difference between an ordered broadcast and a regular broadcast:

The difference between ordered and out-of-order broadcasts: After we send out the unordered broadcast, we don't know who receives it first, let's not say that after receiving it, don't send it to another one. Ordered broadcasts can do this by setting the priority to determine the order of the broadcast recipients.

How to send an ordered broadcast:

Sendorderedbroadcast (Intent, receiverpermission);

Sendorderedbroadcast (Intent, receiverpermission, Resultreceiver,

Scheduler, Initialcode, Initialdata, Initialextras)

Intent, broadcast, all matching this intention to receive the receiver broadcast.

Receiverpermission This is permission, a receiver must hold to receive your broadcast. If NULL, the requirement is not approved.
Resultreceiver your own broadcastreceiver as the final broadcast receiver.
Scheduling custom handlers to schedule resultreceiver callbacks; If null, the main thread in the context is held.
Initialcode the initial value of a result code. It is usually activity.result_ok. This value is-1; for other int types can also, such as 0,1,2;
Initialdata the initial value of a result data. Normally null, is a String type;
Initialextras an additional initial value for the result. Usually empty, is Bundle;

Orderly broadcasting requires attention to:

1, the level of the broadcast level, the level value is between 1000 to 1000, the greater the value, the higher the priority;
2, the same level receive is successively random, and then to the level of low received broadcast;
3, the same level of reception is the random, if the first received the broadcast truncated, the same level of exception recipients are unable to receive the broadcast, the way to truncate the broadcast:abortbroadcast ();
4, can cut off the continued transmission of the broadcast, high-level broadcasts received by the broadcast, can decide whether the clock broadcast is truncated.
5, experimental phenomenon, in this method sent to the broadcast, the Code registration method, received the broadcast sequence is: the priority, code
Code Demo:

Here's a demonstration of sending an ordered broadcast, and passing data between broadcasts through intent, because the block on permissions has already been said, so in order to broadcast here no longer described, through sendorderedbroadcast (intent, receiverpermission); method sends an ordered broadcast, the second parameter is set to NULL: Here we register the broadcast via XML

1) define the broadcast

public class MyBroadcast2 extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { System.out.println ("MyBroadcast2 started!"); /receive the parameter System.out.println (Intent.getstringextra ("test") in the intent passed over by the sendorderedbroadcast and/or add another parameter bundle bundle= New Bundle (); Bundle.putstring ("Test2", "I am the data stored from MYBROADCAST2");//encapsulate it as a bundle object and let the next broadcast receive Setresultextras (Bundle);}}
public class MyBroadcast1 extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) { System.out.println ("Mybroadcast started!"); /receive the parameter System.out.println (Intent.getstringextra ("test") in the intent passed over by the sendorderedbroadcast;// Get another data bundle Bundle=getresultextras (true) that came from the previous broadcast; System.out.println (bundle.getstring ("test2"));}}
2) Declare the broadcast in Androidmanifest.xml:

        <receiver android:name= ". MyBroadcast1 ">            <intent-filter android:priority=" ">                <action android:name=" Com.xin.action.broadcast "/>            </intent-filter>        </receiver>        <receiver android:name=" . MyBroadcast2 ">            <intent-filter android:priority=" ">                <action android:name=" Com.xin.action.broadcast "/>            </intent-filter>
The above declared broadcast, MYBROADCAST2 than MYBROADCAST1 priority!

3) Send an ordered broadcast

Intent intent=new Intent ("Com.xin.action.broadcast"); Intent.putextra ("Test", "I am sendorderedbroadcast sent over data!"); Sendorderedbroadcast (Intent,null);
Test results:



Since the Mybroadcast2 priority (1000) is higher than Mybroadcast1 (900), the broadcast is sent out through Sendorderedbroadcast, first received by Mybroadcast2, and then Mybroadcast2 is passed to Mybroadcast1 with Setresultextras set by another parameter, and then Mybroadcast1 receives the broadcast, also through Getresultextras (true) Receive the data from the Mybroadcast2, so the above results appear!

The test found that when using Sendbroadcast, if the use of Setresultextras or Getresultextras in the Broadcastreceiver , the program will error, because it is not sending an orderly broadcast!

Attention:
1,
if it is registered in the code, we can use filter.setpriority (1000), to set its priority, here does not illustrate!

2. If we want the ordered broadcast to be received in a broadcastreceiver, no longer the next broadcast execution, you can call its abortbroadcast (); interrupt the broadcast send, the subsequent broadcast will not receive!


Sending of sticky broadcasts (asynchronous broadcasts)

In the online professional name is different, some people say it is sticky broadcast, also some people said it is an asynchronous broadcast, not to discuss its professional terminology, first let us understand what it is used, it is different from the ordinary broadcast is when the broadcast canceled registration, and then send a sticky broadcast, Broadcast after re-registration can still receive the sticky broadcast sent over the message!

The biggest difference between a regular broadcast and a sticky broadcast:

We know that we first register the broadcast, then send the broadcast, then no matter what the broadcast can be received, then if we first send a broadcast, then register the broadcast it:

Normal broadcast: not registered broadcast--Send broadcast----register for broadcast--not receiving broadcast

Sticky Broadcast: Non-registered broadcast----Send broadcast----to register a broadcast--to receive a broadcast, and to receive the last broadcast message to send a broadcast multiple times

This is the difference between the two, let's give you an example by code, our broadcast is a very resident broadcast registered in code:

The page contains only three test buttons:


We register the broadcast in the activity of the registered broadcast: Registeractivity, which cancels the registration of the broadcast in the OnPause method of its life cycle UNREGISTERBR

Define broadcast Broadcastreceiver Receiver=new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) {String action=intent.getaction (); int Count=intent.getintextra ("Count", 0); System.out.println ("action=" +action+ ", count=" +count);}};/ /registered broadcast @overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.register); Intentfilter filter=new intentfilter ();//Add Broadcast actionfilter.addaction (" Com.xin.action.broadcast "), Filter.addaction (" Com.xin.action.sticky.broadcast "); Registerreceiver (receiver, filter);} Unregister broadcast @overrideprotected void OnPause () {super.onpause (); System.out.println ("Registerbroadactivity onpause!"); Unregisterreceiver (receiver);}
To send a broadcast in mainactivity:

    Define a variable to count the number of clicks to send a sticky broadcast, and then test whether the receive of the sticky broadcast is the last broadcast    private int count; @Overridepublic void OnClick (View v) {Intent Intent=null;switch (V.getid ()) {case r.id.btn_send1://issue broadcast sendbroadcastintent=new Intent ("Com.xin.action.broadcast "); Sendbroadcast (intent); Break;case r.id.btn_send2://issued a sticky broadcast sendstickybroadcastcount++;intent=new intent (" Com.xin.action.sticky.broadcast "); Intent.putextra (" Count ", count); Sendstickybroadcast (intent); break;case r.id.register://Start the Registration broadcast page Intent=new Intent (mainactivity.this,registerbroadactivity.class); startactivity (Intent); Break;}} @Overrideprotected void Onresume () {super.onresume (); count=0; System.out.println ("Mainactivity onresume!");}
Note that when you send a sticky broadcast, we need to add the ability to send sticky broadcasts in androidmanifest.xml, or we'll get an error:

<uses-permission android:name= "Android.permission.BROADCAST_STICKY"/>
Test and conclusion:

When we click the Send Sendbroadcast button 3 times--Click the Register button, console no output results

When we click the Send Sendstickybroadcast button 4 times--Click the Register button, the console output results: action=com.xin.action.sticky.broadcast,count=4

That's the difference between a regular broadcast and a sticky broadcast.
Sendbroadcast sent out of the broadcast, if there is no broadcast to register, then the ad will not be received, when re-registration of the broadcast, will not receive
Sendstickybroadcast sent out of the broadcast, if there is no broadcast to register, then the ad will not be received at this time, when the re-registration of the broadcast, will receive, and will accept the sendstickybroadcast sent to the last broadcast, So the above output results in click Send Stickybroadcast 4 times, Count becomes 4, then when re-register the broadcast, the console will output the results count=4;
the last intent issued by Sendstickybroadcast will be preserved, and the next time Recevier is active, it will be accepted .

When we need to remove the sticky broadcast, call the method: Removestickybroadcast (Intent), you can clear off the sticky broadcast

There is also a way to send the broadcast: Sendstickyorderedbroadcast (), test in this method sent to the broadcast, code registration method, received the broadcast order: marked priority, code registration, no priority; If there is no priority, the code registration is received as the first.

The above gives you several ways to broadcast operations:

Send broadcast: Sendbroadcast (Intent Intent),sendbroadcast (Intent Intent,String receiverpermission) ;

Send ordered broadcasts: Sendorderedbroadcast (Intent intent,string receiverpermission);

Send Sticky broadcast: sendstickybroadcast (Intent Intent);

There is another way: Sendstickyorderedbroadcast ();(not studied, do not know how much to use)


In the Android broadcast operation, we should also know:

1. The broadcast receivers are run in the main thread (main threads, UI threads) by default, whether for ordered or unordered broadcasts. You can specify the thread to run the broadcast sink by using the last parameter in the Registerreceiver (receiver, filter, Broadcastpermission, Scheduler) method in the program. You can also set it in the Manifest.xml file (set android:process in the Intent-filter tab).

2, we registered in the Code broadcast Registerbroadcast 10 times, then the wide advertisement sent over the time will receive 10 times, write off the broadcast only once!

3. Each time the broadcast arrives, the Broadcastreceiver object is recreated, and the OnReceive () method is called, and the object is destroyed when it finishes executing. When the OnReceive () method is not completed within 10 seconds, Android will consider the program unresponsive. So in the broadcastreceiver can not do some more time-consuming operation, the side will pop up the ANR (Application noresponse) dialog box, if you need to complete a more time-consuming work, should be sent by Intent to Service, by S Ervice to finish. It is not possible to use a child thread here because the Broadcastreceiver life cycle is short, and the child thread may not have finished broadcastreceiver before it ends. Once the broadcastreceiver is over, the broadcastreceiver process can easily be killed when the system needs memory because it belongs to the empty process (the process without any active components). If its host process is killed, then the working child thread will be killed. So using sub-threading to solve is unreliable.

4. The time-consuming operation should be initiated by the broadcast service to perform the operation

Broadcastreceiver receiver=new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) { Intent intent=new Intent (context,testservice.class); StartService (Intent);}};

Android Tour 17 in Android for broadcast use

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.