Android Broadcast Mechanism Analysis

Source: Internet
Author: User

Android Broadcast Mechanism Analysis
1.1. Broadcast Overview
Android broadcast is different from broadcast in life. It refers to notifications generated after events in the system. Android broadcast is a one-way notification that does not care whether the receiver receives or processes the broadcast.
Android uses BraodcastReceiver to listen to the broadcast sent by the system. Different BraodcastReceiver sets different fliter to distinguish the broadcast type. Some broadcast listeners require the corresponding permissions.

1.2. Register Broadcast
BraodcastReceiver must be registered before it can be used for listening. There are two ways to register:
1.2.1. Static Registration
Register the corresponding handler in AndroidManifest. xml and set the action to listen.


Here, mycycler is the class that inherits BroadcastReceiver. it overwrites the oncycler method and processes the broadcast in the oncycler method. The tag sets the filter to receive the specified action broadcast. Static registration features: listening is performed regardless of whether the application is active or not. An action can be a custom action or an action that comes with the system.


1.2.2. Dynamic Registration
Dynamic registration is to register the listener for BroadcastReceiver in the program.

MyReceiver receiver = new MyReceiver (); // create a filter and specify the action to receive the broadcast IntentFilter filter = new IntentFilter ("MyReceiver_Action") of the same action "); // register the broadcast receiver registerReceiver (receiver, filter); register the broadcast in the activity. The broadcast must be canceled at the end of the activity. Generally, BroadcastReceiver is registered in onStart and BroadcastReceiver is canceled in onStop, the life cycle of the broadcast receiver following the Activity // deregister the broadcast receiver unregisterReceiver (receiver ER );


1.3. Lifecycle
BroadcastReceiver has a life cycle of about 8 seconds. If you do something in onReceive () for more than 8 seconds, an error message indicating that the ANR (Application Not Response) Program has no Response will be reported. Its life cycle starts from the onReceive () method of callback to the result returned by this method. Therefore, if you want to perform time-consuming operations after receiving the broadcast, it is best to put it in the service, and the sub-thread is not good. When the sub-thread is not finished, the BroadcastReceiver has been destroyed.


1.4. Send Broadcast
1.4.1. Three broadcast sending methods in Android
Broadcast is divided into three types: "Normal broadcasts", "Ordered broadcasts", and "Sticky broadcast )". Normal broadcast is completely asynchronous and can be received by all broadcast recipients at the same time (logically). The efficiency of message transmission is relatively high, but the disadvantage is: the receiver cannot pass the processing result to the next receiver, and cannot terminate the propagation of the broadcast Intent. However, the ordered broadcast is based on the priority stated by the receiver (declared in the android of the intent-filter element: in the priority attribute, the greater the number, the higher the priority level. value range:-1000 to 1000 (in fact, the maximum value can be int, that is, 2147483647 ). You can also call setPriority () of the IntentFilter object to set the value. The receiver receives the broadcast in sequence. For example, if the level of A is higher than that of B and the level of B is higher than that of C, broadcast is first transmitted to A, then to B, and finally to C. After A receives the broadcast, it can store the data in the broadcast. When the broadcast passes to B, B can obtain the data stored by A from the broadcast. Context. sendBroadcast () sends a normal broadcast. All subscribers have the opportunity to obtain and process the broadcast. Context. sendOrderedBroadcast () sends an ordered broadcast. The system executes the receivers one by one based on the priority level stated by the receiver. The previous receiver has the right to terminate the broadcast. BroadcastReceiver. abortBroadcast () if the broadcast is terminated by the previous receiver, the subsequent receiver will no longer be able to obtain the broadcast. For ordered broadcast, the previous receiver can store the processing result in the broadcast Intent and then pass it to the next receiver. Context. sendStickyBroadcast () is used to send stickybroadcast. To use this api, you need permission for android. manifest. permission. BROADCAST_STICKY: The sticky broadcast feature that Intent will be retained until the broadcast event ends, and this broadcast has no so-called 8-second limit. That is, if the onReceive method takes too long to execute, after 8 seconds, the system sets the broadcast as the candidate that can be killed. Once the system resources are insufficient, the broadcast will be killed so that the broadcast will not be executed.
1.5. Broadcast priority
1.5.1. Basic Principles
The order in which receivers receive unordered broadcasts is ordered (determined by the priority)
Receivers that receive unordered broadcasts can also set priority.
Dynamic Registration broadcast has a higher priority than static registration broadcast.
A dynamic receiver with the same priority, first registered first received
For static receivers with the same priority, the order of receiving broadcasts is the same as that of String [] java. io. File. list ().
Ps: It is worth noting that the receiving sequence of static receivers with the same priority is uncertain because of File. the Order returned by the list () method is uncertain. To view the receiving order of a receiver, it is best to experiment with a large number of apk names.

1.5.2. ordered Broadcast
Assume that there are five receivers with the following priority:
1. Dynamic A (priority = 1)
2. Dynamic B (priority = 2)
3. Dynamic C (priority = 2)
4. Static D (priority = 1)
5. Static E (priority = 2)
And B is registered before C.
The actual receiving order should be
B C E A D
That is to say, if the priority of the static receiver is higher than that of the dynamic receiver, the static receiver receives the broadcast first (for example, receives the SMS broadcast)

1.5.3. Non-ordered Broadcast
High-priority dynamic receivers> low-priority dynamic receivers> high-priority static receivers> low-priority static Receivers

1.6. Only dynamic broadcast source code analysis is supported
Some broadcasts cannot be received by static receivers, such as ACTION_SCREEN_ON. When the screen is lit, the system sends this broadcast.
1. void com. android. server. PowerManagerService. initInThread () 2. Java code 3. void initInThread () {4 .?? 5. mScreenOnIntent = new Intent (Intent. ACTION_SCREEN_ON); 6. mScreenOnIntent. addFlags (Intent. FLAG_RECEIVER_REGISTERED_ONLY); 7. mScreenOffIntent = new Intent (Intent. ACTION_SCREEN_OFF); 8. mScreenOffIntent. addFlags (Intent. FLAG_RECEIVER_REGISTERED_ONLY); 9 .?? 10 .}

Intent. FLAG_RECEIVER_REGISTERED_ONLY is set in Intent. Therefore, to receive the message, you must dynamically register the broadcast receiver ACTION_SCREEN_OFF.

1.6.1. Description of FLAG_RECEIVER_REGISTERED_ONLY
Public static final int
FLAG_RECEIVER_REGISTERED_ONLY
Added in API level 1
If set, when sending a broadcast only registered receivers will be called -- no
BroadcastReceiver components will be launched.
Constant Value: 1073741824 (0x40000000)
ACTION_BATTERY_CHANGED (when the batterpower changes, the system sends this broadcast)
Void com. android. server. BatteryService. sendIntent ()
Java code 1. private final void sendIntent () {2. // 3. intent intent = new Intent (Intent. ACTION_BATTERY_CHANGED); 4. intent. addFlags (Intent. FLAG_RECEIVER_REGISTERED_ONLY5.Pack up the values and broadcast them to everyone6.7 .}

1.7. Analysis of the broadcast registration process
1.7.1. Static registration process
When PackageManagerService starts up, it is responsible for initial PMS Scanning System directories one by one during startup to parse the apk file. Static broadcast receivers are handled by the way when PMS is doing this.
PMS will parse the manifest file of the apk, find the handler registered here, and load it To the memory.
The sequence of PMS initialization scan directories:
System/framework
System/app
Vendor/app
Data/appd
Rm/app-private
We can see how PMS parses manifest during initialization and stores the element in the memory. The receiver is saved to the owner's member variable receivers. The owner type is
Android. content. pm. PackageParser. Package: scanPackageLI returns a Package object that contains manifest information.

1.7.2. dynamically register a consumer
Dynamic Registration will eventually call the registerReceiver function in AMS, and all dynamically registered referers will be saved to the mReceiverResolver member variable of AMS. We have analyzed how static broadcast and dynamic broadcast are registered. Static broadcast is the responsibility of PackageManagerService and saved to its member variable mReceivers. Dynamic broadcast is the responsibility of ActivityManagerService and saved to its member variable mReceiverResolver.
1.8. Broadcast sending Process Analysis
1.8.1. Analysis
The sendBroadCast function in Context is implemented in ContextImpl. The following six functions are related to sending broadcast:

void android.app.ContextImpl.sendBroadcast(Intent intent)void android.app.ContextImpl.sendBroadcast(Intent intent, String receiverPermission)void android.app.ContextImpl.sendOrderedBroadcast(Intent intent, String receiverPermission)void android.app.ContextImpl.sendOrderedBroadcast(Intent intent, String receiverPermission,BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData,Bundle initialExtras)void android.app.ContextImpl.sendStickyBroadcast(Intent intent)void android.app.ContextImpl.sendStickyOrderedBroadcast(Intent intent, BroadcastReceiverresultReceiver, Handler scheduler, int initialCode, String initialData, BundleinitialExtras)
It can be divided into three groups: 1 normal broadcast, 2 Ordered broadcast, and 3 Sticky broadcast. Either of them will be processed by AMS. If it is a non-ordered broadcast, mParallelBroadcasts will store all the dynamic receivers, and when merged, mParallelBroadcasts will be set to null, so it will not be merged into receivers, if it is an ordered broadcast, mParallelBroadcasts will be merged into receivers. Then, no matter which broadcast is used, scheduleBroadcastsLocked will be called to continue processing, and finally to the processNextBroadcast function. Whether the broadcast is ordered, that is, it is set through the Boolean variable ordered.

1.8.2. Summary
The sending process is divided into two types: scheduleBroadcastsLocked, ordered broadcast, non-ordered broadcast, and non-ordered broadcast. First process the dynamic receiver, then process the static receiver ordered broadcast simultaneously process the dynamic receiver and the static receiver first merge the dynamic receiver and the static receiver to maintain the same order as the priority, the priority is higher than the previous, otherwise, the order remains unchanged. If the static receiver has the same priority as the dynamic receiver, the dynamic receiver goes first.






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.