Overview of Android broadcastreceiver broadcast mechanism

Overview of Android broadcast mechanism Android broadcast is divided into two aspects: Broadcast sender and broadcast receiver. Generally, broadcastreceiver refers to broadcast receiver (broadcast receiver). As a communication method between Android components, broadcast can be used in the following scenarios:

1. Message communication within the same component within the same app (between single or multiple threads); 2. Message communication between different components within the same app (single process); 3. Message communication between different components with multiple processes in the same app; 4. Message communication between components of different apps; 5. Message communication between Android system and app under specific circumstances.

From the perspective of implementation principle, the broadcast in Android uses observer mode and message based publish / subscribe event model. Therefore, from the perspective of implementation, broadcasting in Android decouples the sender and receiver of broadcasting to a great extent, making the system easy to integrate and expand. The key points of the specific implementation process are roughly summarized as follows: 1 The broadcast receiver registers with AMS (activity manager service) through binder mechanism; 2. The broadcast sender sends a broadcast to AMS through the binder mechanism; 3. AMS finds the broadcastreceiver that meets the corresponding conditions (intentfilter / permission, etc.) and sends the broadcast to the corresponding message cycle queue of broadcastreceiver (generally activity); 4. The message loop executes to get this broadcast and call back the onReceive () method in the broadcastreceiver.

For different broadcast types and different broadcastreceiver registration methods, the specific implementation will be different. But the overall process is roughly the same.

Therefore, the broadcast sender and the broadcast receiver belong to the two ends of message publishing and subscription in the observer mode respectively, and AMS belongs to the intermediate processing center. The execution of the broadcast sender and the broadcast receiver is asynchronous. The broadcast sent will not care whether there is a receiver to receive, nor is it sure when the receiver can receive it. Obviously, the overall process is very similar to eventbus.

In the specific scenarios where the broadcasting mechanism listed above can be used, the applicability in practical application is analyzed:

The first case: for message communication (between single or multiple threads) in the same component within the same app, the broadcast mechanism will not be used in practical applications (although it can be used). Such problems can be directly handled by using extended variable scope, interface based callback or handler post / handler message. If the broadcast mechanism is applicable, Obviously, some feelings of "killing chickens and cattle" will be too "heavy";

The second case: Message Communication (single process) between different components within the same app. In some complex cases, it is difficult to deal with such requirements simply by relying on interface based callback. At this time, you can directly use eventbus. Relatively speaking, eventbus is very suitable for dealing with such requirements because it is aimed at unified processes and can be easily decoupled. See the document eventbus, a communication tool between Android components / controls.

Situation 3, 4 and 5: since message communication between different processes is involved, it is very appropriate to use the broadcast mechanism according to the actual service. The following is a summary of the specific knowledge points in Android broadcasting.

2.BroadcastReceiver

Customize broadcastreceiver

The custom broadcast receiver needs to inherit the base class broadcastreceive and implement the abstract method onReceive (context, intent) method. After receiving the corresponding broadcast, the broadcast receiver will automatically return to onReceive (..) method. By default, the broadcast receiver is also running in the UI thread, so the onReceive method cannot perform too time-consuming operations. Otherwise, anr will be. Generally, according to the actual business requirements, the onReceive method involves the interaction with other components, such as sending notification, starting service, etc. The following code snippet is the customization of a simple broadcast receiver:

Broadcastreceiver registration type broadcastreceiver can be divided into two registration types: static registration and dynamic registration. 1). Static registration: directly in Android manifest XML file. The rules are as follows:

Among them, the attribute Android: exported -- whether this broadcastreceiver can receive broadcasts from other apps is interesting by default. Its default value is determined by whether there is an intent filter in the receiver. If there is an intent filter, the default value is true, otherwise it is false. (similarly, the default value of this attribute in activity / service follows this rule.) at the same time, it should be noted that the setting of this value is bounded by application or application user ID, rather than process (an application may contain multiple processes); Android: name -- the name of this broadcastreceiver class; Android: permission - if set, the broadcast sent by the broadcast sender with corresponding permission can be received by this broadcastreceiver; Android: process -- the process in which broadcastreceiver runs. The default is app process. Independent processes can be specified (the four basic components of Android can specify their own independent processes through this attribute)

Common registration forms are:

Among them, intent filter specifies that this broadcast receiver will be used to receive a specific broadcast type. In this example, it is used to receive the broadcast sent by the system itself when the network state changes or starts up. When this app is started for the first time, the system will automatically instantiate mybroadcastreceiver and register it in the system.

It was often said before that the statically registered broadcast receiver can still receive the corresponding broadcast even if the app has exited, but this description may no longer be valid since Android 3.1. See the later part of this article for specific analysis.

2). Dynamic registration: during dynamic registration, there is no need to register the < receiver / > component in androidmanifest. Directly in the code, you can dynamically register broadcastreceiver in the program by calling the registerreceiver function of context. Registerreceiver is defined as follows:

registerReceiver(BroadcastReceiver receiver,IntentFilter filter)

registerReceiver(BroadcastReceiver receiver,IntentFilter filter,String broadcastPermission,Handler scheduler)

Typical writing examples are as follows:

Note: in all designs related to observer mode in Android, once register is involved, unregister must be required at the corresponding time. Therefore, the above example needs unregisterreceiver (mbaroadcastreceiver) in ondestroy() return.

When this activity is instantiated, mybroadcastreceiver will be dynamically registered in the system. When this activity is destroyed, the dynamically registered mybroadcastreceiver will no longer receive the corresponding broadcast.

3. Broadcast transmission and broadcast type

It is often said that "send broadcast" and "receive broadcast". On the surface, broadcast is regarded as an entity in Android broadcast mechanism. In fact, this entity itself does not exist as a so-called "broadcast" object, but is expressed as "intention". The definition process of defining broadcast is actually the definition process of corresponding broadcast "intention", and then it is defined by the broadcast sender The intention is sent out. After being received by the corresponding broadcastreceiver, the onreceive() function will be called back.

The next code snippet shows the definition process of an ordinary broadcast and sends it out. Where setaction (..) Corresponds to the action in intentfilter in broadcastreceiver.

Intent intent = new Intent(); intent. setAction(BROADCAST_ACTION); intent. putExtra("name","qqyumidi"); sendBroadcast(intent);

According to the transmission mode of broadcasting, it can be divided into the following types: 1 Normal broadcast: ordinary broadcast 2 System broadcast: system broadcast 3 Ordered broadcast: ordered broadcast 4 Sticky broadcast: sticky broadcast (deprecated in Android 5.0/api 21, which is no longer recommended. Correspondingly, there is also sticky ordered broadcast, which has also been deprecated) 5 Local broadcast: app in app broadcast

The following summarizes various types of transmission methods and their characteristics. 1). Normal broadcast: normal broadcast is defined here as an intention defined by the developer, with context sendBroadcast_ "AsUser"(intent,...) Form. The specific methods you can use are: sendbroadcast (intent) / sendbroadcast (intent, receiverpermission) / sendbroadcast asuser (intent, userhandler) / sendbroadcast asuser (intent, userhandler, receiverpermission). Ordinary broadcasts will be received by the corresponding registered interest (intent filter matching), and the order is out of order. If there are corresponding permission requirements when sending a broadcast, broadcastreceiver also needs corresponding permission if it wants to receive this broadcast.

2). System broadcast: multiple system broadcasts are built in the Android system. As long as the basic operation of the mobile phone is involved, the corresponding system broadcast will basically be issued. Such as: startup, network state change, photographing, screen off and on, insufficient lighting, etc. Each system broadcast has a specific intent filter, which mainly includes specific actions. After the system broadcast is sent, it will be received by the corresponding broadcastreceiver. The system broadcast is in the system. When a specific event occurs, the system will send it automatically.

3) Ordered broadcast: ordered broadcast "ordered" in the ordered broadcast refers to the broadcast receiver, which means that the broadcast sent is received by the broadcastreceiver in sequence. The definition process of ordered broadcasting is no different from that of ordinary broadcasting, except that its main sending method is changed to: sendordered broadcast (intent, receiver permission,...).

The main features of ordered broadcasting are summarized as follows: 1 > when multiple currently registered and valid broadcastreceivers receive ordered broadcasting, they are received in sequence. The sequence judgment standard follows: all valid dynamically registered and statically registered broadcastreceivers in the current system are sorted from large to small according to the priority attribute value, For dynamic broadcasting and static broadcasting with the same priority, dynamic broadcasting will rank first.

2> The first received broadcastreceiver can truncate this ordered broadcast so that the later broadcastreceiver will no longer receive this broadcast, or modify the broadcast so that the later broadcastreceiver can parse and obtain the wrong parameter value after receiving the broadcast. Of course, in general, such operations are not recommended for ordered broadcasting, especially for ordered broadcasting in the system.

4) Sticky broadcast: sticky broadcast (deprecated in Android 5.0/api 21, which is no longer recommended. Correspondingly, there is sticky ordered broadcast, which has also been deprecated).

Since it has been deprecated, there is no more summary here.

5) Local broadcast: intra app broadcast (APP applications here are bounded by app application processes)

It can be seen from the above description that the broadcast in Android can communicate directly across processes or even across apps, and the registration is exported. The default value is true when there is an intent filter. Therefore, potential security risks are as follows:

1. Other apps may issue targeted broadcasts matching the current app intent filter, resulting in the current app continuously receiving and processing broadcasts;

2. Other apps can register an intent filter consistent with the current app to receive broadcasts and obtain broadcast specific information.

In either case, these security risks do exist. Therefore, the most common schemes to increase security are:

1. For the broadcast sent and received inside the same app, set the exported attribute to false artificially, so that the broadcast not sent inside the app will not be received;

2. Add corresponding permission for permission verification during broadcast transmission and reception;

3. When sending a broadcast, specify the packet name of a specific broadcast receiver, specifically through intent Setpackage (packagename) is specified in, so that this broadcast will only be sent to the matching valid broadcast receivers in the app in this package.

Intra app broadcasting can be understood as a form of local broadcasting. Both the sender and receiver of broadcasting belong to the same app. In actual business requirements, intra app broadcasting may indeed be needed. At the same time, when using in app broadcasting instead of global broadcasting, more consideration is given to the security problem in Android broadcasting mechanism.

Compared with global broadcasting, the advantages of intra app broadcasting are as follows:

1. Higher safety;

2. More efficient.

Therefore, the encapsulated localbroadcastmanager class is given in the Android V4 compatibility package to uniformly handle the broadcasting problems in app applications. The use method is almost the same as the usual global broadcasting, except that when registering / unregistering the broadcast receiver and sending the broadcast, the calling context becomes a single instance of localbroadcastmanager.

The code snippet is as follows:

4. Broadcast receivers with different registration methods call back the specific type of context in onReceive (context, intent)

1). For the statically registered contextreceiver, the context in the callback onReceive (context, intent) specifically refers to the receiverrestrictedcontext;

2). For the dynamically registered contextreceiver of the global broadcast, the context in the callback onReceive (context, intent) specifically refers to the activity context;

3). For the contextreceiver dynamically registered through the localbroadcastmanager, the context in the callback onReceive (context, intent) specifically refers to the application context.

Note: intra application broadcasts sent by localbroadcastmanager can only be received by contextreceivers dynamically registered by localbroadcastmanager (contextreceivers dynamically registered by static registration or other methods cannot be received).

5. Important changes of broadcast mechanism related APIs in different Android API versions

1). Android5. 0 / API level 21 start sticky broadcast and ordered sticky broadcast are expired, and it is no longer recommended to use in the future;

2).” The statically registered broadcast receiver can still receive even if the app has exited and the corresponding broadcast is sent out, but this description may not be valid since Android 3.1“

Since Android 3.1, the system has added parameters to the broadcast related flag of intent, namely flag_ INCLUDE_ STOPPED_ Packages and flag_ EXCLUDE_ STOPPED_ PACKAGES。 FLAG_ INCLUDE_ STOPPED_ Packages: contains packages that have been stopped (stop: the process in which the package is located has exited) flag_ EXCLUDE_ STOPPED_ Packages: does not contain packages that have been stopped

The main reasons are as follows:

From Android 3 1. At the beginning, the system itself increases the tracking of whether all apps are currently running. When sending a broadcast, regardless of the broadcast type, the system directly adds the value of flag by default_ EXCLUDE_ STOPPED_ The flag of packages causes that even statically registered broadcast receivers cannot receive broadcasts for apps whose processes have exited.

See the official Android documentation for details: http://developer.android.com/about/versions/android-3.1.html#launchcontrols

Therefore, since the system broadcast is sent directly from within the system, the intent flag value cannot be changed. Therefore, 3.1 for the statically registered broadcastreceiver receiving the system broadcast, if the app process has exited, it will not receive the broadcast.

However, for customized broadcasts, you can copy this flag to flag_ INCLUDE_ STOPPED_ Packages enables the statically registered broadcastreceiver to receive broadcasts and start the application process even if the app process has exited, but the broadcastreceiver is newly created at this time. Intent intent = new Intent(); intent. setAction(BROADCAST_ACTION); intent. addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); intent. putExtra("name","qqyumidi"); sendBroadcast(intent);

Note 1: for a dynamically registered broadcastreceiver, since this registration and deregistration are performed in other components (such as activities), it is not affected by this change.

Note 2: before 3.1, it is believed that many apps may listen to various system broadcasts through static registration, so as to carry out some business processing (for example, the instant app has exited, can still receive, can start the service, etc.), After 3.1, the change of static registration to accept broadcasting will directly lead to the infeasibility of such schemes. Therefore, setting the service and app to different processes has become a feasible alternative to realizing such requirements.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>