What do you need to know about BroadcastReceiver?

Source: Internet
Author: User
Tags app service

What do you need to know about BroadcastReceiver?

I spoke about the Service of one of the four major components a few days ago. Today I want to talk about its brother BroadcastReceiver. I am quite entangled in writing this article, because the broadcast receiver is indeed relatively simple, but you should not think that it is simple and will not be connotation. Maybe we will discuss it one more day.

In practice, we will first introduce the basic knowledge, and later we will talk about some minor knowledge about the receipt sequence of BroadcastReceiver.

 

BroadcastReceiver Concept

BroadcastReceiver is mainly used to listen to the broadcast information sent by the system or application, and then uses the broadcast information as the corresponding logic. In other words, it is actually a global listener, communication between different components in the system. Sometimes it is used to transmit a small amount of data with a low sending frequency. However, if the data sending frequency is relatively high or the number is large, it is not recommended to use the broadcast receiver to receive the data, this is very inefficient because BroadcastReceiver has a large overhead for receiving data.

 

Basic use of BroadcastReceiver

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

1 public class MyBroadcastReceiver extends BroadcastReceiver {2 @ Override3 public void onReceive (Context arg0, Intent arg1) {4 // code logic used by the broadcast receiver to receive the broadcast after execution 5} 6}

Simple and perfect. To implement a broadcast receiver, we only need to rewrite an onReceiver () function. If the broadcast receiver receives the broadcast, it will execute this function; however, the premise is that the broadcast receiver needs to be registered. Generally, there are only two ways to register BroadcastReceiver. One is static registration and the other is dynamic registration, after registration, the broadcast receiver starts to listen to the broadcast messages sent between systems or applications.

 

Static RegistrationMethod: Open the AndroidManifest list file, such as Activity, Service, add a data item for registration, as follows:

<Cycler android: name = ". MyBroadcastReceiver"> <intent-filter> <! -- The action naming rule is generally recommended as package name. intent. class name --> <action android: name = "com. net168.testabl. intent. mybroadcastreceiver "/> </intent-filter> </receiver ER>

The broadcast receiver of static registration is a global listener resident in the system. That is to say, if your application is configured with a static BroadcastReceiver and you have installed the application, whether or not the application is running, the broadcast recipients are already resident in the system. However, some people will be very depressed about how to destroy the broadcast Receiver. In fact, you only need to call PackageManager to disable the Receiver. Is it simple and practical?

 

Dynamic RegistrationMethod: Use registerReceiver (receiver, filter) to register the broadcast receiver. The Code is as follows:

// The filter is used to set the interceptor IntentFilter = new IntentFilter ("com. net168.testabl. intent. mybroadcastreceiver "); MyBroadcastReceiver receiver = new MyBroadcastReceiver (); // dynamically register the broadcast receiver registerReceiver (receiver, filter );

A dynamically registered broadcast receiver can only listen to broadcast messages when it executes the registerReceiver (filter) and process the broadcast messages accordingly.

Destroy a dynamically registered BroadcastReceiver as follows:

// Cancel the Dynamic Registration of the broadcast receiver unregisterReceiver (receiver );

After the registration is revoked, the broadcast receiver will no longer listen to the broadcast messages of the system.

 

Some differences between static registration of BroadcastReceiver and Dynamic Registration of BroadcastReceiver

1. Once installed, the static-registered broadcast receiver is resident in the system and does not need to be restarted to wake up the receiver. The dynamically registered broadcast receiver starts to listen with the application's life cycle, unregisterReceiver is used to cancel the listener. In addition, if the application exits, an error is returned if the registered receiver application is not revoked.

2. When the broadcast receiver starts an activity or service through intent, if the intent cannot match the corresponding component. Dynamic Registration of the broadcast receiver will cause the application to report errors, and the static registration of the broadcast receiver will not report any errors, because since the application is installed, the broadcast receiver and the application have been separated.

 

Broadcast receiver Mechanism

When the system or application sends a broadcast, it will scan all the broadcast recipients in the system and send the broadcast to the corresponding receiver through action matching, after receiving the broadcast, the receiver will generate an instance of the broadcast receiver and execute the onReceiver () method. Note that the life cycle of the instance is only 10 seconds, if oncycler () is not completed within 10 seconds, the system reports an error. In addition, after onReceiver () is executed, the instance will be destroyed, so do not perform time-consuming operations in onReceiver, it will not create a sub-thread in it to process the business (because the sub-thread may not be finished, and the receiver will be recycled). The correct solution is to call activity or service through intent to process the business.

 

Send Broadcast

There are three types of broadcast:Ordinary broadcast and ordered broadcast, there is also a rare sticky Broadcast.

In order to meet various application requirements, Android has set two Broadcast sending methods, each with its own characteristics. Generally, normal broadcasts can be used to send broadcasts that need to be notified to each broadcast receiver, such as after the broadcast is started; ordered broadcast applies to scenarios that require specific interception, such as blacklist text messages and phone calls.

 

Normal Broadcast: Normal broadcast is completely asynchronous and can be received by all receivers at the same time (logically). message transmission is highly efficient and cannot interrupt broadcast propagation.

Intent intent = new Intent (); intent. setAction ("com. net168.testabl. intent. mybroadcastreceiver "); intent. putExtra ("data", "hello"); // send the normal broadcast sendBroadcast (intent );

SendBroad (intent) is used to send normal broadcast messages.

 

Ordered Broadcast: After an ordered Broadcast is sent, the Broadcast receiver receives the Broadcast according to the predefined priority. A broadcast with a higher priority is received, but the broadcast will not be transmitted to the next receiver during its onReceiver () execution. At this time, the current broadcast receiver can terminate the broadcast and continue to spread downward, you can also modify the data in the intent and then spread it to the next broadcast receiver.

SendOrderedBroadcast () is used to send ordered broadcasts.

// Send the ordered broadcast sendOrderedBroadcast (intent, null );

For the ordered broadcast receiver, we can perform some operations in the onReceiver.

Public void onReceive (Context arg0, Intent intent) {// gets the bundle data Bundle bundle = getResultExtras (true) of the previous broadcast; // true: A new Bundle is created when the previous broadcast has no results; false: No Bundle is created. putString ("key", "168168"); // put the bundle data into the broadcast and pass it to the next broadcast receiver setResultExtras (bundle ); // terminate the broadcast and send it to the next broadcast receiver abortBroadcast ();}

In ordered broadcast, we can transmit processed data to the receiver of the broadcast, or call abortBroadcast () to terminate broadcast propagation.

 

Viscous Broadcast: This broadcast is not commonly used. We can use sendStickyBroadcast () to send this type of broadcast information. The biggest feature of this broadcast is that when the viscous broadcast is sent, the last sticky broadcast will be stuck in the operating system. If a new broadcast receiver with Dynamic Registration that matches the broadcast is registered within a period of time after the sticky broadcast is sent, the broadcast message will be received, although this broadcast was sent before the broadcast receiver was registered, this broadcast receiver is equivalent to normal broadcast for static registration.

 

The order in which the broadcast receiver receives the broadcast.

Note: The priority range of the broadcast receiver is 1000 for the maximum mark in the Google document, but the actual maximum level is Integer. MAX (that is, 2147483647 ).

  Static broadcast receiving ProcessorIt is the responsibility of PackageManagerService. When the mobile phone starts or the APP is newly installed, PackageManagerService scans all installed apps on the mobile phone and sends AndroidManifest. the information about the registration broadcast in xml is parsed and stored in a Global static variable. Note that:

1. The order of the PackageManagerService scan directories is as follows:

System/framework-> system/app-> vendor/app-> data/app-> drm/app-private

2. When the file is in the same directory: In the returned order of file. list. (Digression: All applications under data/Appare installed by the user and appear in the form of com.xxx.xxx-1.apk. Therefore, if you plan to use applications such as mobile phone manager, you need to carefully study the package name and strive for file. list () is the first to compete under the zhuqiao road --- receives broadcasts after startup .)

 

Dynamic broadcast receiving ProcessorActivityManagerService is responsible for this. When the APP service or process gets up, It executes the code logic for registering broadcast receipt, that is, loading, and finally stores it in another global static variable. Note that:

1. This is not static. After the program is killed, the registered dynamic broadcast receiver will also be removed from the global variable until the next program starts and then registers dynamic broadcast, of course, the order here has also changed once.

2. the sorting of broadcast is not complete here. Only the registration order is recorded, and there is no matching priority.

 

When a broadcast is sent, the receiver receives the following message:

If the broadcast is an ordered broadcast, the dynamic broadcast processor and the static broadcast processor are combined to process the broadcast messages and finally determine the order in which the broadcast is received:

1. First receiving with a higher priority 2. Dynamic and Static broadcast receivers with the same priority; Dynamic and Static broadcast receivers with the same priority 3. Dynamic broadcast receivers with the same priority or static broadcast receivers with the same priority; static: scanned before scanning. Dynamic: registered before registration. When a broadcast is a normal broadcast, it has the following receiving order:1. Ignore the priority. The dynamic broadcast receiver takes precedence over the static broadcast receiver. 2. The dynamic broadcast receiver with the same priority or the static broadcast receiver with the same priority. The static broadcast receiver is classified as the first scanned and then scanned, dynamic: the number of registered instances must be greater than the value of registered instances. By enjoy wind chimes
Source: Http://www.cnblogs.com/net168/
The copyright of this article is shared by the author and the blog Park. You are welcome to reprint this article. However, you must keep this statement without the author's consent and provide a connection to the original article clearly on the article page. Otherwise, you will not be reposted next time.

Related Article

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.