Analyze some of the things you need to know about Broadcastreceiver

Source: Internet
Author: User

The service of one of the four components was pulled over the previous days, and today it is time to start talking about its brother Broadcastreceiver. Write here I am quite tangled, because the broadcast receiver is indeed relatively simple, but you do not think that simple is not connotation, perhaps we slowly explore another piece of heaven and earth.

The usual practice is to introduce the basics, and later we'll talk about the order of reception of Broadcastreceiver and some other trivia.

The concept of Broadcastreceiver

The function of Broadcastreceiver is mainly used to listen to the broadcast information sent by the system or application, and then according to the broadcast information as the corresponding logic processing; Speaking of popular point is actually a kind of global listener , to realize the communication between different components in the system. Sometimes it is used as a small transmission and low frequency of data, but if the data are sent at a higher frequency or a larger number is not recommended to use the broadcast receiver, because this is not efficient, Because the overhead of broadcastreceiver receiving data is still relatively large.

Basic use of Broadcastreceiver

Let's take a look at the radio receiver's Code, as follows:

 1  public  class  Mybroadcastreceiver extends   Broadcastreceiver { 2   @Override  3  public  void   OnReceive (Context arg0, Intent arg1) { 4  //  used to implement code logic that the broadcast receiver executes after receiving the broadcast  5  Span style= "color: #000000;" >}  6 } 

Simple and perfect, the implementation of a broadcast receiver simply requires us to rewrite a function onreceiver (), if the broadcast receiver will execute the function after receiving the broadcast, but this premise is required to register this broadcast receiver , in general, There are only two ways to register Broadcastreceiver, one is static registration , the other is dynamic registration , and the broadcast receiver begins to listen to the broadcast message sent between the system or application after registering.

How to register statically : Open the Androidmanifest manifest file, add a data item like activity, service, and register as follows:

<receiverAndroid:name=". Mybroadcastreceiver ">    <Intent-filter>      <!--the naming conventions for action are generally recommended as: package name. Intent. Class name -      <ActionAndroid:name= "Com.net168.testBcr.intent.mybroadcastreceiver"/>    </Intent-filter></receiver>

A statically registered broadcast receiver is a global listener that resides in the system, meaning that if you configure a static broadcastreceiver in your application and you install the app regardless of whether the app is running, the broadcast recipient is already resident in the system . But some people will be very depressed how to destroy this broadcast receiver, in fact, as long as the call Packagemanager receiver disabled on the line, simple and practical?

Dynamic Registration Method: Use Registerreceiver (receiver, filter) to register the broadcast receiver, the code is as follows:

// Filter is the interceptor that sets receiver New Intentfilter ("Com.net168.testBcr.intent.mybroadcastreceiver"new  mybroadcastreceiver (); // Dynamic registration of broadcast receiver Registerreceiver (receiver, filter);

Dynamically registered broadcast receivers only perform registerreceiver (receiver, filter) to start listening for broadcast messages and treat broadcast messages as appropriate.

Destroy a dynamically registered Broadcastreceiver as follows:

// revoke the dynamic registration Unregisterreceiver (receiver) of the broadcast receiver ;

The broadcast recipient will no longer listen to the broadcast message of the system after the deregistration.

Some differences between statically registered Broadcastreceiver and dynamically registered Broadcastreceiver

1, the static registration of the broadcast receiver once installed in the system, do not need to restart the wake-up receiver; dynamically registered broadcast receivers with the application life cycle, by the registerreceiver began to listen, by the Unregisterreceiver revocation monitoring, It is also important to note that if the app exits, no cancellation of the registered recipient app will cause an error.

2. When the broadcast receiver initiates an activity or service through intent, if the corresponding component cannot be matched in intent. Dynamically registered broadcast receivers will result in an application error, while statically registered broadcast receivers will not have any error, since the broadcast receiver has been disconnected from the app since the application installation is complete.

Broadcast receiver mechanism

When the system or application broadcasts, it will scan all the broadcast receivers in the system, send the broadcast to the appropriate recipient through action matching, and the receiver will generate an instance of the broadcast receiver after receiving the broadcast, and execute the Onreceiver () method in it; It is particularly important to note that this instance The life cycle is only 10 seconds , and if the end Onreceiver () is not executed within 10 seconds, the system will error. In addition, after Onreceiver () is executed, the instance will be destroyed, so do not perform time-consuming operations in Onreceiver (), nor create sub-threading operations in it (because it is possible that the recipient is recycled if the child thread is not processed) The right approach is to invoke activity or service processing through intent.

Send broadcast

There are three types of broadcasts: regular broadcasts and ordered broadcasts, and another less commonly used sticky broadcast .

Android to meet a variety of application requirements, set up two ways to send broadcasts, each has its own characteristics. General broadcast can be applied in the case of the need to notify each broadcast receiver, such as the start of the end of the transmission of the broadcast, while the orderly broadcast is used in situations requiring specific interception such as blacklist text messages, telephone interception.

General broadcast : The General broadcast is completely asynchronous and can be received by all receivers at the same time (logically), with high efficiency of message delivery and inability to interrupt broadcast propagation.

New Intent (); Intent.setaction("Com.net168.testBcr.intent.mybroadcastreceiver"); Intent.putextra (" Data "," Hello "); // Send General broadcast Sendbroadcast (intent);

Send a normal broadcast message via Sendbroad (intent).

Orderly broadcast : After sending an ordered broadcast, the broadcast recipient will receive broadcast in order of pre-declared priority. Priority high priority receives the broadcast, and during its onreceiver () execution, the broadcast does not propagate to the next recipient, at which point the current broadcast receiver can terminate the broadcast to continue to propagate downward, or the data in the intent can be modified and then propagated to the next broadcast recipient.

Send an ordered broadcast via Sendorderedbroadcast ().

// send an ordered broadcast null);

For the orderly broadcast receiver, we can do some more onreceiver

 Public void onreceive (Context arg0, Intent Intent) {  // get the bundle data for the last broadcast bundle bundle = Getresultextras ( true); //  true: The previous broadcast has no results when creating a new Bundle;false: Do not create bundle bundle.putstring ("Key", "168168");   // put bundle data into the broadcast to the next broadcast recipient Setresultextras (bundle);  // end broadcast to the next broadcast recipient abortbroadcast ();}    

In an ordered broadcast, we can send the processed data to the subsequent broadcast receivers in the previous broadcast receiver, or call Abortbroadcast () to end the broadcast propagation.

Sticky broadcast : This broadcast is less commonly used, and we can send this type of broadcast information through Sendstickybroadcast (), the greatest feature of which is that when a sticky broadcast is sent, the last sticky broadcast is stuck in the operating system. If, for a period of time after the sticky broadcast is sent, if there is a new dynamic registered broadcast receiver registered with the broadcast, the broadcast message will be received, although the broadcast is sent before the broadcast receiver registers, and the other point, for statically registered broadcast receivers, is equivalent to ordinary broadcast.

the broadcast recipient receives the broadcast order

Note: The priority range of the broadcast receiver the maximum level indicated on the Google document is 1000, but the actual maximum is Integer.max (that is, 2147483647).

  the processor that is received by the static broadcast is owned by Packagemanagerservice, and when the phone is launched or a new app is installed, Packagemanagerservice scans all installed apps in the phone, The information about registered broadcasts in Androidmanifest.xml is parsed and stored in a global static variable. It is important to note that:

1. The order of Packagemanagerservice scan directories is as follows:

System/framework, System/app, Vendor/app, Data/app, drm/app-private

2, when in the same directory: according to File.list () return order. (digression: Because the application in the Data/app is installed by the user, and are all in the form of com.xxx.xxx-1.apk, so if you intend to do mobile phone butler and other applications, need to study the package name, to fight in the File.list () The top of the bridge to seize---priority to receive the start-up broadcast. )

the processor that is received by the dynamic broadcast is owned by Activitymanagerservice, and when the app's service or process is up, it executes the code logic of the registered broadcast receipt, which is loaded and stored in an additional global static variable. It is important to note that:

1, this is not immutable, when the program is killed, the registered dynamic broadcast receiver will also be moved out of the global variables, until the next time the program starts, and then the dynamic broadcast registration, of course, the order has been changed once.

2, there is not a complete sequence of broadcasting, only record the order of registration, there is no combination of priority processing.

When the broadcast is issued, the broadcast receiver receives the following order:

If the broadcast is an ordered broadcast, then the dynamic broadcast processor and the static broadcast processor are combined to process the broadcast message, which ultimately determines the order in which the broadcast is received:

1, high priority first receive2. Static and dynamic broadcast receivers with priority3, with the priority of the dynamic broadcast receiver or the same priority static broadcast receiver; sub-static: First scan of greater than after scanning, dynamic: first registered greater than after registration. when a broadcast is a normal broadcast, it has the following order of reception:1, ignoring the priority, the dynamic broadcast receiver takes precedence over the static broadcast receiver2, with the priority of the dynamic broadcast receiver or the same priority static broadcast receiver; sub-static: First scan of greater than after scanning, dynamic: first registered greater than after registration. enjoy wind chimes
Source: http://www.cnblogs.com/net168/
This article is copyright to the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph statement, and in the article page obvious location to the original connection, or next time not to you reproduced.

Analyze some of the things you need to know about 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.