Android four components of the Broadcastreceiver

Source: Internet
Author: User

Broadcastreceiver is a global listener. A broadcast message that listens to the system globally. Because he is a global listener, he can easily implement communication between different components in the system.

1. Create Broadcastreceiver

 Public class extends broadcastreceiver {    @Override    publicvoid  onreceive (context context, Intent Intent) {                //  When the supervisor hears the broadcast message, this method is executed.         String Content=intent.getstringextra ("content");         You are sending: "+content, Toast.length_short). Show ();    }}
View Code

Broadcastreceiver the broadcast is received, the OnReceive method is executed. You can use intent to receive data information.

2. Register Broadcastreceiver

(1) Static registration

Static registration, that is, in the Androidmanifest.xml file, register Broadcastreceiver.

 <  receiver  android:name  = ". Myreceiver " >  <  intent-filter  >  <  action  android:name   ></ action  >  </ intent-filter  >  </ receiver  >  

(2) Dynamic registration

Dynamic registration, is registered in the code broadcastreceiver, if using dynamic registration, you can register in the activity Onresume (), OnPause, or registered in OnCreate (), Ondestory logout.

// instantiate a broadcast sink    New myreceiver ();     // Filter the broadcast, here "Com.example.MY_LISTENER" is I custom, can write casually, broadcast time consistent can    New Intentfilter ();    Intentfilter.addaction ("Com.example.MY_LISTENER");     // Register a broadcast      registerreceiver (Myreceiver, Intentfilter);  // logout of the broadcast  //unregisterreceiver (myreceiver)
View Code

There are two overloads of the Registerreceiver method.

First type:registerreceiver (broadcastreceiver receiver, intentfilter filter)

First parameter: The Broadcastreceiver (broadcast receiver) responsible for receiving the broadcast;

The second parameter: is the intention filter;

Second type: Registerreceiver (receiver, filter, broadcastpermission, scheduler)

First parameter: The Broadcastreceiver (broadcast receiver) responsible for receiving the broadcast;

Second parameter: Intent filter (which broadcasts can be received by this receiver);

The third parameter: Broadcast permission;

Fourth parameter: hander;

(3) The difference between "static registration" and "Dynamic registration"!

When a broadcastreceiver is registered statically, the corresponding broadcast can be received regardless of whether the application is started or not.
When registering dynamically, if Unregisterreceiver () is not executed, the method cancels the registration, which is the same as static. However, if the method is executed, the broadcast will not be accepted once it has been executed.

(4) Note: Permission duplication Behavior

If the Androidmanifest.xml (function manifest file) is registered, the receiver cannot receive the broadcast when the method is re-registered.

If the Androidmanifest.xml (feature manifest file) does not have permissions registered, the method registration is not received. When the method does not have registration permission, receiver can receive the broadcast when the function list is registered.

3. Type of broadcast and sending

General broadcast : for receiver, the normal broadcast is completely asynchronous and can be received by all receivers at the same time, and the Message delivery speed table is faster.

Send broadcast:

Button_start.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//send broadcast still need to use intentIntent Intent =NewIntent (); //This action is the one we configured for receiver in Androidmanifest.xml.Intent.setaction ("Com.example.MY_LISTENER"); //incoming parameters to receiverIntent.putextra ("Content", "Hello Receiver"); //Send broadcastSendbroadcast (Intent); }        });
View Code

Receive broadcast:

 Public class extends broadcastreceiver {    @Override    publicvoid  onreceive (context context, Intent Intent) {                //  When the supervisor hears the broadcast message, this method is executed.         String Content=intent.getstringextra ("content");         You are sending: "+content, Toast.length_short). Show ();    }}
View Code

ordered broadcast : by assigning a priority to receiver (receiver), the system arranges a high priority receiver to receive the broadcast, and then the priority receiver transmits the broadcast to the lower priority receiver. You can use Abortbroadcast () in a high-priority receiver to terminate broadcast delivery so that it is not received by a lower priority receiver.

In addition, the results of processing and related information can be passed through the Setresultextras (Bundle) method in high priority receiver. Passed to the next receiver (using Getresultextras (TRUE) to receive the data deposited by the previous recipient).

Note: When receiver with the same priority, the system executes which receiver is random. If none of the priority levels are specified, dynamic registration (code registration) is the first to receive the broadcast.

Specify receiver's priority level

(1) in the Androidmanifest.xml file, specify the priority by Android:priority= "".

  <receiverAndroid:name=". Myreceiver ">      <Intent-filterandroid:priority= "Ten">           <ActionAndroid:name= "Com.example.MY_LISTENER"></Action>      </Intent-filter>  </receiver>

(2) specified by Intentfilter's setpriority ().

Note: The scope of the priority -1000~1000

Cases:

Define three recipients

MyReceiver1

public class Myreceiver extends Broadcastreceiver {    @Override public    void OnReceive (context context, Intent Intent) {        //to multiply the received num by 10.        int num = Intent.getintextra ("num", 0);        num = num * TEN;        Bundle B = new bundle ();        B.putint ("num", num);        Pass the processing result to the next recipient        , Setresultextras (b);        Toast.maketext (Context, "1, Received:" + string.valueof (num),                toast.length_short). Show ();    }}
View Code

MyReceiver2

public class MyReceiver2 extends Broadcastreceiver {    @Override public    void OnReceive (context context, Intent Intent) {        //to multiply the received num by 10.        int num = Getresultextras (true). GetInt ("num");        num = num * TEN;        Bundle B = new bundle ();        B.putint ("num", num);        Pass the processing result to the next recipient        , Setresultextras (b);        Toast.maketext (Context, "2, Received:" + string.valueof (num),                toast.length_short). Show ();                Terminates the broadcast to the next recipient.        //abortbroadcast ();    }}
View Code

MyReceiver3

public class MyReceiver3 extends Broadcastreceiver {    @Override public    void OnReceive (context context, Intent Intent) {                //to multiply the received num by 10.        int num = Getresultextras (true). GetInt ("num");        num = num * TEN;        Toast.maketext (Context, "3, Received:" + string.valueof (num),                toast.length_short). Show ();    }}
View Code

Send an ordered broadcast:

Button_start = (Button) Findviewbyid (r.id.button1);        Button_start.setonclicklistener (New Onclicklistener () {            @Override public            void OnClick (View v) {                Intent Intent = new Intent ();                Intent.setaction ("Com.example.MY_LISTENER");                Give the first receiver incoming parameter                intent.putextra ("num", 1);                Send broadcast, note: Here is Sendorderedbroadcast                sendorderedbroadcast (intent, NULL);            }        });
View Code

Here Sendorderedbroadcast () is used to send an ordered broadcast, which has two parameters and the first parameter is intent. The second parameter is permission, and if you assign a permission to a broadcast, only receiver with that permission can receive it.

4 Life cycle

The life cycle of the broadcastreceiver is very brief: receive the broadcast →onreceive () → End;

So in the OnReceive method, do not perform time-consuming tasks, if the method executes more than 10 seconds, Android will think that the program is unresponsive, and pop up the ANR dialog box. If you have to take time-consuming tasks to consider, open the service in OnReceive to execute, but do not use the thread, because the Broadcastreceiver life cycle is very short, there may be a child thread is not finished, Broadcastreceiver has exited.

If the process where the Broadcastreceiver is located ends, although there may be a new thread in the process that the user started, but because there are no active components within the process, the system will prioritize the process when memory is tight, This causes the Broadcastreceiver-initiated child threads to not finish.

Tip: We can also monitor system broadcasts. For example, the system "start complete" broadcast, I can implement the boot entry. Network changes and so on.

Special Broadcastreceiver.

Localbroadcastmanager Local Broadcast

Sticky broadcast Sticky Broadcast

Orderedbroadcastreceiver Orderly Broadcasting

Stickyorderedbroadcast Sticky ordered broadcast

Related information:

Http://www.cnblogs.com/trinea/archive/2012/11/09/2763182.html

http://yangguangfu.iteye.com/blog/1063732

Android four components of the Broadcastreceiver

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.