Android Broadcast mechanism analysis

Source: Internet
Author: User

1.1. Introduction to Broadcasting
        Android radio differs from the broadcast concept in life, which refers to the notification after an event is generated in the system. Android broadcasts are a one-way notification of whether the recipient is receiving processing or how to handle the broadcast.
        Android uses Braodcastreceiver to listen to broadcasts from the system, and different braodcastreceiver distinguish the type of listening broadcast by setting different fliter. Some broadcasts require the appropriate permission to listen.

1.2. Register for the broadcast
        Braodcastreceiver must be registered to have the ability to listen, there are two ways to register:
1.2.1. Static Registration
        By registering the corresponding receiver in the Androidmanifest.xml and setting the action to listen


        Where Myreceiver is the class that inherits the Broadcastreceiver, the Onreceiver method is overridden, and the broadcast is processed in the Onreceiver method. <intent-filter> tag sets the filter to receive the specified action broadcast. Static registration Mode features: Regardless of whether the application is active, will listen. The action can be either a custom action or an action that comes with the system.


1.2.2. Dynamic Registration
Dynamic registration is the broadcastreceiver completion of monitoring registration in the program
Myreceiver receiver = new Myreceiver ();//Create a filter and specify the action to be used to receive the broadcast with the action intentfilter filter = new Intentfilter ("Myrec Eiver_action ");//Register the broadcast receiver Registerreceiver (receiver, filter); Register the broadcast in activity, you must unregister the broadcast at the end of the activity, typically in OnStart The broadcastreceiver is registered in the OnStop, the broadcast receiver follows the Activity's life cycle//unregisters the broadcast receiver Unregisterreceiver (receiver), which cancels the broadcastreceiver;


1.3. Life cycle
        Broadcastreceiver life cycle of only about 8 seconds, if within onreceive () do more than 8 seconds of things, will report the ANR (application not Response) program unresponsive error message. Its life cycle ends when the callback OnReceive () method starts and the method returns results. Therefore, if you want to do time-consuming operation after receiving the broadcast, it is best to put it into the service, the sub-thread is not good, when the child thread is not finished, Broadcastreceiver has been destroyed.


1.4. Send a broadcast
1.4.1. Three ways to send broadcasts in Android
        Broadcasts are divided into three different types: "Normal broadcasts", "ordered broadcast (Ordered broadcasts)", and "Sticky Broadcast (Sticky broadcast)". The normal broadcast is completely asynchronous and can be received by all broadcast receivers at the same time (logically), with high efficiency of message delivery, but the disadvantage is that the receiver cannot pass the processing result to the next recipient and cannot terminate the propagation of the broadcast Intent, but the ordered broadcast is the priority level declared by the receiver ( Declared in the android:priority attribute of the intent-filter element, the higher the number of precedence, the greater the value range: 1000 to 1000 (in fact, the maximum can be int maximum value is: 2147483647). You can also call the Intentfilter object's SetPriority () to set up) and receive the broadcast sequentially by the receiver. For example, if the level of a is higher than b,b, then the broadcast is passed first to a, then to B, and finally to C. When a broadcast is received, the data can be deposited into the broadcast and, when broadcast is transmitted to B, B can receive a deposit of a data from the broadcast. Context.sendbroadcast () sends a normal broadcast, and all Subscribers are given the opportunity to obtain and process it. Context.sendorderedbroadcast () sends an ordered broadcast, and the system executes the receiver sequentially, based on the priority level declared by the receiver, and the preceding receiver has the right to terminate the broadcast. Broadcastreceiver.abortbroadcast () If the broadcast is terminated by the previous receiver, the subsequent recipient will no longer be able to obtain the broadcast. For ordered broadcasts, the previous receiver can store the processing results in a broadcast Intent and then pass them on to the next recipient. Context.sendstickybroadcast () is to send sticky broadcasts, using this API requires permission from Android. Manifest.permission.BROADCAST_STICKY, sticky broadcast is characterized by the Intent will remain until the end of the broadcast event, and this broadcast does not have the so-called 8-second limit, that is to say, if the OnReceive method execution time is too long, more than 8 Seconds, the system will be set to kill the broadcast candidate, once the system resources are not enough, it will kill the broadcast and let it not execute.
1.5. Broadcast Priority
1.5.1. Basic Principles
The order in which the receivers receiving an unordered broadcast receive broadcasts is ordered (determined by priority order)
Receivers that receive out-of-order broadcasts can also set the priority
Dynamic registration broadcast priority higher than static registered broadcast
A dynamic receiver of equal priority, first registered first received
Static receivers of equal priority, the order in which the broadcasts are received is consistent with the order of string[] Java.io.File.list ()
Ps: One thing to note here is that the order of reception of static receivers of equal priority is uncertain, because the order of file.list () is uncertain, and if you need to see the order in which a receiver is received, it is best to experiment with a large number of apk names.

1.5.2. Ordered broadcast
Assuming 5 receivers like the next 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 prior to C
Then the actual receive order should be
B C E A D
That is, if the static receiver takes precedence over the priority of the dynamic receiver, then the static receiver receives the broadcast first (such as receiving SMS broadcasts)

1.5.3. Non-ordered broadcast
        Dynamic receiver high-priority > Dynamic receiver Low priority > static receiver High priority > static receiver Low-priority

1.6. Broadcast source analysis can only be dynamically accepted
Some broadcasts, we cannot receive with 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, so if you want to receive it, you must dynamically register the broadcast sink Action_screen_off as well.

1.6.1. Notes on 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 would be called--no
Broadcastreceiver components would be launched.
Constant value:1073741824 (0x40000000)
Action_battery_changed (the system sends this broadcast when the battery charge changes)
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. Broadcast Registration Process Analysis
1.7.1. The process of statically registering Receiver
        Static receiver registration is initiated by the Packagemanagerservice when the initial PMS at boot time will be on the system some directory scanning, parsing apk file. Static broadcast receivers are handled by the PMS when doing this.
The PMS parses the APK's manifest file, finds the receiver registered here, and loads it into memory.
The order in which the PMS initializes the scanned directories:
System/framework
System/app
Vendor/app
Data/appd
Rm/app-private
        We see how the PMS parses the manifest at initialization and stores the element in memory where receiver is stored in the member variable receivers of owner, and the type of owner is
Android.content.pm.PackageParser.Package This means that Scanpackageli returns the package object that already contains the manifest information.

1.7.2. The process of dynamically registering Receiver
        Dynamic registration is eventually called to the Registerreceiver function in AMS, and eventually all dynamically registered receiver are saved to the member variable mreceiverresolver of AMS. Static broadcast and dynamic broadcast how to register, we have all finished analysis. Static broadcast is packagemanagerservice responsible for saving to its member variable mreceivers, which is activitymanagerservice responsible for saving to its member variable mreceiverresolver.
1.8. Broadcast Transmission Process Analysis
1.8.1. Analysis
The implementation of the Sendbroadcast function in the Context is in Contextimpl, and there are six functions associated with sending the 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)
        Can be divided into 3 groups: 1 General Broadcasting, 2 Ordered broadcast, 3 Sticky broadcast. Either way, it will be processed by AMS at the end.        If non-ordered broadcasts, then mparallelbroadcasts will store all dynamic receivers, and then when merging, Mparallelbroadcasts is set to NULL, so it is not merged into receivers, if ordered Broadcast, then Mparallelbroadcasts will be merged into receivers, and then, regardless of the broadcast, the final call schedulebroadcastslocked continue processing, eventually to Processnextbroadcast function. The broadcast is ordered, which is set by the Boolean variable ordered.

1.8.2. Summary
        The sending process is divided into two types (schedulebroadcastslocked), ordered broadcast and non-ordered broadcast, and non-ordered broadcast. The receiver is processed first, then the static receiver ordered broadcast simultaneously processes both the dynamic receiver and the static receiver, first merging the dynamic receiver with the static receiver, maintaining the same order of precedence, high priority in front, otherwise the order is unchanged. The static receiver and the dynamic receiver have the same priority, the dynamic receiver is in front.






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.