Reprint: Android Summary series: Android broadcast mechanism
1.Android Broadcast Mechanism overview
Android broadcasts are divided into two areas: the broadcast sender and the broadcast receiver, usually broadcastreceiver refers to the broadcast recipient (broadcast receiver). Broadcast as a means of communication between Android components, you can use the following scenarios:
1. Message communication within the same component inside the same app (between single or multiple threads);
2. Message communication between different components within the same app (single process);
3. The same app has multiple processes for message communication between different components;
4. Message communication between components in different apps;
The 5.Android system communicates with the app in certain situations.
From the implementation principle, the broadcast in Android uses the Observer pattern, the message-based publish/subscribe event model. Therefore, from the point of view of implementation, the broadcast in Android will greatly decouple the sender and recipient of the broadcast, which makes the system easy to integrate and easily expand. The specific implementation process points are summarized as follows:
1. The broadcast recipient broadcastreceiver through the binder mechanism to the AMS (Activity Manager Service) registration;
2. The broadcasting sender transmits the broadcast to AMS through the binder mechanism;
3.AMS finds the broadcastreceiver that meet the appropriate conditions (intentfilter/permission, etc.) and sends the broadcast to the corresponding message loop queue in Broadcastreceiver (typically activity);
4. Message loop execution get this broadcast, callback Broadcastreceiver in the OnReceive () method.
For different broadcast types, and different broadcastreceiver registration methods, the implementation will be different. But the overall process is roughly the same.
Thus, the broadcast sender and the broadcast receiver belong to both ends of the message publication and subscription in The Observer pattern, and AMS belongs to the middle processing center. The execution of the broadcast sender and the broadcast receiver is asynchronous, and the outgoing broadcast does not care whether or not the recipient receives it, or when the recipient is actually receiving it. Clearly, the overall process is very similar to Eventbus.
In the scenario described above, the broadcast mechanism can be used in specific scenarios, the applicability of practical applications is now analyzed:
The first scenario: message communication within the same component inside the same app (between single or multiple threads), which is certainly not used in the actual application (although it can be used), whether it's using an extended variable scope, an interface-based callback, or a handler-post/ Handler-message and other ways, can directly deal with such problems, if the application of broadcasting mechanism, it is obvious that some "kill chicken sledgehammer" feeling, will be too "heavy";
The second situation: the message communication between different components within the same app (a single process), for this kind of requirement, in some teaching complex cases simply rely on the interface-based callback and other ways bad processing, at this time can directly use Eventbus, relatively speaking, eventbus because of the unified process, It is ideal for dealing with such requirements and is easily decoupled. See the file "Eventbus of communication between Android components/controls."
Third scenario: Because of the communication between different processes, it is very appropriate to use the broadcast mechanism according to the actual business. The following is a summary of specific knowledge points in Android broadcasts.
2.BroadcastReceiver
Custom Broadcastreceiver
Custom broadcast receivers need to inherit the base class Broadcastreceivre and implement the abstract method OnReceive (context, intent) method. When the broadcast receiver receives the corresponding broadcast, it automatically returns to OnReceive (..) Method. By default, the broadcast sink is also running on the UI thread, so the OnReceive method cannot perform too time-consuming operations. Otherwise it will be ANR. In general, depending on the actual business requirements, the OnReceive method involves interactions with other components, such as sending notification, starting the service, and so on.
The following code snippet is a simple broadcast receiver customization:
Public classMybroadcastreceiverextendsBroadcastreceiver { Public Static FinalString TAG = "Mybroadcastreceiver"; Public Static intm = 1; @Override Public voidOnReceive (Context context, Intent Intent) {LOG.W (TAG,"Intent:" +intent); String name= Intent.getstringextra ("name"); LOG.W (TAG,"Name:" + name + "m=" +m); M++; Bundle Bundle=Intent.getextras (); }}
Broadcastreceiver Registration Type
Broadcastreceiver can be divided into two types of registration: Static registration and dynamic registration.
1). Static registration:
Register directly in the Androidmanifest.xml file. The rules are as follows:
<receiverandroid:enabled=["true"| "False"]android:exported=["true"| "False"]android:icon= "drawable resource"Android:label= "string resource"Android:name= "string"android:permission= "string"android:process= "string" >. . .</receiver>
Among them, the attributes that need attention
android:exported--This broadcastreceiver can receive broadcasts from other apps, the default value of this property is a bit of meaning, and its default is determined by whether or not intent-filter in receiver, If there is a intent-filter, the default value is true, otherwise false. (Again, the default value for this property in Activity/service follows this rule) at the same time, it should be noted that this value is set to application or application user ID, rather than process-bounded (one application may contain multiple processes) ;
android:name--this broadcastreceiver class name;
android:permission--if set, broadcast sent by the broadcast sender with the corresponding permission can be received by this broadcastreceiver;
The process where the android:process--broadcastreceiver runs. The default is the app's process. You can specify a separate process (Android four basic components can specify their own independent process through this property)
Common forms of registration are:
<receiverAndroid:name=". Mybroadcastreceiver " > <Intent-filter> <ActionAndroid:name= "Android.net.conn.CONNECTIVITY_CHANGE" /> </Intent-filter> <Intent-filter> <ActionAndroid:name= "Android.intent.action.BOOT_COMPLETED" /> </Intent-filter></receiver>
Where Intent-filter is assigned this broadcast sink to receive a specific broadcast type. In this example, the broadcast that is issued by the system itself when receiving a network state change or when booting is turned on. When the app is first launched, the system automatically instantiates the mybroadcastreceiver and registers it with the system.
Used to say: Static registered broadcast receiver even if the app has exited, the main has a corresponding broadcast issued, still can receive, but this kind of description from the beginning of Android 3.1 may no longer be established, detailed analysis is detailed in the later part of this article.
2). Dynamic registration:
When registering dynamically, you do not need to register the <receiver/> component in Androidmanifest. You can dynamically register Broadcastreceiver in your program by invoking the Registerreceiver function of the context directly in your code. The registerreceiver is defined as follows:
Registerreceiver (broadcastreceiver receiver, Intentfilter filter) Registerreceiver (Broadcastreceiver receiver, Intentfilter filter, String broadcastpermission, Handler Scheduler)
A typical example is as follows:
Public classMainactivityextendsActivity { Public Static FinalString broadcast_action = "Com.example.corn"; PrivateBroadcastreceiver Mbroadcastreceiver; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mbroadcastreceiver=NewMybroadcastreceiver (); Intentfilter Intentfilter=NewIntentfilter (); Intentfilter.addaction (broadcast_action); Registerreceiver (Mbroadcastreceiver, Intentfilter); } @Overrideprotected voidOnDestroy () {Super. OnDestroy (); Unregisterreceiver (Mbroadcastreceiver); }}
Note: All designs related to the observer pattern in Android, once the register is involved, must be unregister at the appropriate time. Therefore, the above example needs Unregisterreceiver (Mbroadcastreceiver) in OnDestroy () back.
When this activity is instantiated, Mybroadcastreceiver is dynamically registered to the system. When this activity is destroyed, the dynamically registered Mybroadcastreceiver will no longer receive the corresponding broadcast.
3. Broadcast transmission and broadcast type
Often said "send broadcast" and "receive", on the surface of broadcasting as an entity in the Android broadcasting mechanism, in fact, the entity itself is not in the so-called "broadcast" object exists, but with "intention" (Intent) to express. Define the broadcast definition process, which is actually the corresponding broadcast "intention" of the definition process, and then send the "intention" by the broadcast sender. The OnReceive () function will be recalled after being received by the corresponding broadcastreceiver.
The next snippet shows the definition of a normal broadcast and sends it out. of which Setaction (..) Corresponds to the action in the Intentfilter in Broadcastreceiver.
1 New Intent (); 2 intent.setaction (broadcast_action); 3 Intent.putextra ("name", "Qqyumidi"); 4 Sendbroadcast (intent);
Depending on how the broadcast is sent, it can be divided into the following types:
1.Normal Broadcast: General broadcast
2.System Broadcast: System broadcast
3.Ordered Broadcast: Ordered broadcast
4.Sticky Broadcast: Sticky broadcast (deprecated in Android 5.0/api 21, no longer recommended, corresponding sticky ordered broadcast, also deprecated)
5.Local Broadcast:app in-app broadcast
The following respectively summarizes the various types of transmission and its characteristics.
1). Normal broadcast: General broadcast
The general broadcast is defined here as: the developer's own definition of the intent to Context.sendbroadcast_ "Asuser" (intent, ...) Form. The specific methods you can use are:
Sendbroadcast (Intent)/sendbroadcast (Intent, Receiverpermission)/sendbroadcastasuser (Intent, Userhandler)/ Sendbroadcastasuser (Intent, userhandler,receiverpermission).
The normal broadcast will be received by the corresponding interested (Intent-filter match) registered, and the order is unordered. If there is a corresponding permission requirement to send the broadcast, broadcastreceiver must have the appropriate permissions if you want to receive this broadcast.
2). System Broadcast: Systems broadcast
There are several system broadcasts built into the Android system, and as long as the basic operation of the mobile phone is involved, the corresponding system broadcasts are basically issued. Such as: Turn on Start, network status changes, take pictures, screen off and on, light is insufficient and so on. Each system broadcast has a specific intent-filter, which mainly includes the specific action, which is received by the corresponding Broadcastreceiver after the system broadcast is issued. System broadcast within the system when a particular event occurs, a system is automatically issued.
3) Ordered Broadcast: Orderly broadcast
Orderly broadcasting in the orderly broadcast of "order" is for the broadcast receiver, refers to the broadcast is sent out by the Broadcastreceiver in accordance with sequential reception. The definition process of orderly broadcasting is no different from that of ordinary broadcast, but its main transmission mode is: sendorderedbroadcast (Intent, receiverpermission, ...).
For orderly broadcasting, its main features are summarized as follows:
1> a plurality of Broadcastreceiver receiving ordered broadcasts, which are currently registered and valid, are received in sequence, The order of precedence criteria follows: The broadcastreceiver of all valid dynamic registers and static registrations in the current system are sorted by priority attribute values from large to small, and for dynamic broadcasts and static broadcasts with the same priority, dynamic broadcasts are in front.
2> first received broadcastreceiver can be truncated to this ordered broadcast, so that the latter broadcastreceiver no longer receive this broadcast, you can also modify the broadcast, Causes the subsequent broadcastreceiver to receive a broadcast after parsing the parameter values that are incorrect. Of course, this kind of operation is not recommended for ordered broadcasts in general, especially for ordered broadcasts in the system.
4) Sticky broadcast: Sticky broadcast (deprecated in Android 5.0/api 21, no longer recommended, and the corresponding sticky ordered broadcast, also has deprecated).
Since already deprecated, here no more summarize.
5) Local Broadcast:app in-app broadcast (app app is bounded by app app)
As explained in the previous article, the broadcast in Android can cross-process or even cross-app direct communication, and registration is exported for the case of Intent-filter, the default value is true, thus the potential security risks are as follows:
1. Other apps may have targeted broadcasts that match the current app Intent-filter, causing the current app to receive broadcasts and process them continuously;
2. Other apps can register intent-filter that are consistent with the current app to receive broadcasts and get broadcast specific information.
In either case, these security risks are real. As a result, the most common scenarios for increasing security are:
1. For sending and receiving broadcasts within the same app, the exported attribute is artificially set to false so that the broadcast is not received within the app;
2. When the broadcast is sent and received, the corresponding permission are added for authorization verification;
3. When sending a broadcast, specify the package name of the particular broadcast receiver, specified by Intent.setpackage (PackageName), so that the broadcast will only be sent to a valid broadcast receiver within the app that matches it in the package.
App-in-app broadcasts can be interpreted as a form of partial broadcast, where both the sender and receiver of the broadcast belong to an app. In real business needs, app-in-app broadcasts may actually need to be used. At the same time, the use of in-app broadcasts, rather than the form of global broadcasts, is more about security issues in the Android broadcast mechanism.
In contrast to global broadcasts, the app in-app broadcast benefits are:
1. Higher security;
2. More efficient.
To this end, the Android V4 Compatibility Pack gives the encapsulated Localbroadcastmanager class for unified handling of broadcast issues within the app, almost the same way as the usual global broadcasts, just registering/ When you unregister a broadcast receiver and send a broadcast, the keynote context becomes a single instance of Localbroadcastmanager.
The code snippet is as follows:
1 //registerreceiver (Mbroadcastreceiver, intentfilter);2 //registering an in-app broadcast receiver3Localbroadcastmanager = Localbroadcastmanager.getinstance ( This);4 localbroadcastmanager.registerreceiver (Mbroadcastreceiver, intentfilter);5 6 //Unregisterreceiver (mbroadcastreceiver);7 //unregister an in-app broadcast receiver8 Localbroadcastmanager.unregisterreceiver (mbroadcastreceiver);9 TenIntent Intent =NewIntent (); One intent.setaction (broadcast_action); AIntent.putextra ("name", "Qqyumidi"); - //Sendbroadcast (intent); - //send in-app broadcasts theLocalbroadcastmanager.sendbroadcast (Intent);
4. Different registration mode of the broadcast receiver callback OnReceive (context, intent) in the context of the specific type
1). For statically registered Contextreceiver, the context in the callback OnReceive (context, intent) refers specifically to the Receiverrestrictedcontext;
2). For the dynamic registration of global broadcast Contextreceiver, the context in callback OnReceive (context, intent) specifically refers to the activity context;
3). For contextreceiver that are dynamically registered through Localbroadcastmanager, the context in the callback OnReceive (context, intent) specifically refers to the application context.
Note: For in-app broadcasts sent in Localbroadcastmanager mode, Only contextreceiver that are dynamically registered through Localbroadcastmanager can be received (Contextreceiver that are not received by static registration or otherwise dynamically registered).
5. Important changes in broadcast mechanism related APIs in different Android API versions
1). Android5.0/api level 21 begins sticky broadcast and an ordered sticky broadcast expires and is no longer recommended for use;
2). " Statically registered broadcast receivers can still be received, even if the app has exited, primarily with corresponding broadcasts, but this description may no longer be available from Android 3.1.
Android 3.1 started the system in intent with broadcast-related flag added parameters, namely Flag_include_stopped_packages and Flag_exclude_stopped_packages.
Flag_include_stopped_packages: Contains a stopped package (stop: The process where the package is already exiting)
Flag_exclude_stopped_packages: does not contain packets that have been stopped
The main reasons are as follows:
Since Android3.1, the system itself has increased the tracking of whether all apps are currently running. When sending a broadcast, no matter what type of broadcast, the system adds a direct value of flag_exclude_stopped_packages flag, causing even a statically registered broadcast receiver to be able to receive broadcasts for apps that its process has exited.
Learn more about participating in the Android Official document: Http://developer.android.com/about/versions/android-3.1.html#launchcontrols
As a result, for system broadcasts, this intent flag value cannot be changed because it is issued directly inside the system, so the 3.1 begins to broadcast the Broadcastreceiver for a statically registered receive system, and if the app process has exited, it will not be able to receive the broadcast.
However, for custom broadcasts, you can replicate this flag to flag_include_stopped_packages, so that the static registered Broadcastreceiver, even if the app process has exited, can also receive the broadcast, and will start the application process, But this time the broadcastreceiver is re-created.
1 New Intent (); 2 intent.setaction (broadcast_action); 3 intent.addflags (intent.flag_include_stopped_packages); 4 Intent.putextra ("name", "Qqyumidi"); 5 Sendbroadcast (intent);
Note 1: For broadcastreceiver of the dynamic registration type, it is not affected by this change because this registration and de-registration is actually done in other components, such as activity.
Note 2: Before 3.1, it is believed that many apps may listen to various system broadcasts by static registration, in order to do some business processing (such as the Instant app has exited, still can receive, can start service and so on. ), 3.1, the static registration to accept the change of broadcasting mode, will directly lead to such a scheme is no longer feasible. As a result, the process of setting up the service and the app itself into different processes has become a viable alternative to achieving such requirements.
Reprint: Android system broadcast processing mechanism
Broadcasting in an Android system is a means of communication between applications, similar to the event handling mechanism, where broadcast processing is a system-level event-handling process (typically event handling is a control-level). In this process, it is still inseparable from the intent object to understand the broadcast event
process, flexible use of broadcast processing mechanism, often in the key to achieve a special effect, to give a more classic example, which blacklist function, when a call, that is, the generation of a call broadcast, The broadcastreceiver that receive this call broadcast will take this caller number and blacklist
Number to compare, if matching, then the call to do the corresponding processing, such as hanging phone or mute. In this case, it involves the sending and receiving of system broadcasts and the processing of broadcast events.
To compare the knowledge of Android broadcast, list the following mind map:
Other reference Links: Android development process _14 (broadcast mechanism) graphics Android broadcast mechanism Android broadcast mechanism---broadcastandroid learning notes _08. Broadcasting mechanism
Android broadcast mechanism: Broadcast