Android broadcastreceiver Broadcast Mechanism overview _android

Source: Internet
Author: User
Tags deprecated eventbus

Android broadcast mechanism overview
Android broadcasts are divided into two areas: Broadcast senders and broadcast receivers, typically, broadcastreceiver refers to broadcast receivers (broadcast receivers). Broadcast as a means of communication between Android components, you can use the following scenario:

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 message communication between different components of multiple processes;
4. Message communication between components of different apps;
The 5.Android system communicates with the app in specific cases.

From the implementation principle, the broadcast in Android uses the Observer mode, a message based publish/subscribe event model. Thus, from an implementation standpoint, the broadcast in Android will greatly decouple the sender and recipient of the broadcast, making the system easy to integrate and extensible. The specific implementation process points are summarized as follows:
1. The broadcast receiver Broadcastreceiver the AMS (activity Manager Service) through the binder mechanism;
2. Radio senders transmit their broadcasts to AMS through the binder mechanism;
3.AMS find the Broadcastreceiver that meet the corresponding conditions (intentfilter/permission, etc.), send the broadcast to the broadcastreceiver (usually the activity) corresponding message loop queue;
4. Message loop execution get this broadcast and callback the OnReceive () method in Broadcastreceiver.

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

It appears that the broadcast sender and the broadcast receiver belong to both ends of the message release and subscription in the Observer mode, and AMS belongs to the middle processing center. The execution of the broadcast transmitter and the broadcast receiver is asynchronous, and the outgoing broadcast does not care whether the receiver receives it or not, and it is uncertain when the recipient will receive it. Obviously, the overall process is very similar to the Eventbus.

In the scenario described above, the applicability of the actual application is analyzed in the context of the broadcast mechanism that is available:

The First scenario: message traffic within the same app (single or multiple threads) in the same application, which is definitely not going to be used for broadcasting (although it can be used), whether using extended variable scopes, interface callbacks, or handler-post/ Handler-message and other ways, can directly deal with such problems, if the application of broadcasting mechanism, obviously some "kill the chicken" feeling, will show too "heavy";

The second scenario: message communication between different components within the same app (a single process), for this kind of demand, in some teaching complex situation simply rely on the interface of the callback and so on, and so on, can directly use Eventbus and so on, relatively, Eventbus because it is a unified process, it is ideal for handling such requirements and is easily decoupled. You can see the eventbus of the communication tool between the Android components/controls.

Third Chapters scenario: because of the message communication between different processes, it would be appropriate to use the broadcast mechanism based on the actual business. The following is a summary of the specific knowledge points in the Android broadcast.

2.BroadcastReceiver

Custom Broadcastreceiver

Custom broadcast sinks need to inherit base class Broadcastreceivre and implement abstract methods OnReceive (context, intent) methods. When the broadcast receiver receives the broadcast, it automatically returns to OnReceive (..) Method. By default, broadcast sinks are also running on the UI thread, so time-consuming operations cannot be performed in the OnReceive method. Otherwise it will be ANR. In general, depending on the actual business requirements, the onreceive approach involves interacting with other components, such as sending notification, starting a service, and so on.
The following code fragment is a custom for a simple broadcast receiver:

public class Mybroadcastreceiver extends Broadcastreceiver {public
  static final String TAG = "Mybroadcastreceiver"; c2/>public static int m = 1;

  @Override public
  void OnReceive (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 generally 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:

<receiver android: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> 

Where the attributes to be noted
android:exported--This broadcastreceiver can receive broadcasts from other apps, the default value of this property is somewhat interesting, and the default value is determined by whether there is a intent-filter in the receiver, If there is a intent-filter, the default value is true, otherwise false. (Similarly, the default value of this property in Activity/service follows this rule) at the same time, it should be noted that this value is set to be bounded by the application or application user ID, not the process (an application may contain multiple processes) ;
android:name--this broadcastreceiver class name;
android:permission--if set, broadcasts sent by broadcast senders with appropriate permissions can be received by this broadcastreceiver;
The process in which the android:process--broadcastreceiver runs. The default is the app's process. You can specify separate processes (Android's four basic components can specify their own standalone processes through this property)

Common forms of registration are:

<receiver android:name= ". Mybroadcastreceiver ">
  <intent-filter>
    <action android:name=" android.net.conn.CONNECTIVITY_ Change "/>
  </intent-filter>
  <intent-filter>
    <action android:name=" Android.intent.action.BOOT_COMPLETED "/>
  </intent-filter>
</receiver> 

Where Intent-filter because the specified broadcast sink will be used to receive a specific broadcast type. This example gives a broadcast that is used to receive a network state change or when the system itself is turned on at startup. When this app first starts, the system automatically instantiates the mybroadcastreceiver and registers it with the system.

It has always been said that a static registered broadcast receiver, even though the app has exited, is still available for broadcast, but this description may no longer be valid since Android 3.1, as detailed in the later part of this article.

2). Dynamic registration:
When registering dynamically, you do not need to register <receiver/> components in Androidmanifest. Directly in the code by calling the context of the Registerreceiver function, you can dynamically register Broadcastreceiver in the program. Registerreceiver are defined in the following form:

Registerreceiver (broadcastreceiver receiver, Intentfilter filter)

Registerreceiver (broadcastreceiver receiver, Intentfilter filter, String broadcastpermission, Handler Scheduler)

A typical example is the following:

public class Mainactivity extends activity {public
  static final String broadcast_action = "Com.example.corn";
  Private Broadcastreceiver mbroadcastreceiver;

  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);

    Mbroadcastreceiver = new Mybroadcastreceiver ();
    Intentfilter intentfilter = new Intentfilter ();
    Intentfilter.addaction (broadcast_action);
    Registerreceiver (Mbroadcastreceiver, intentfilter);
  }
  
  @Override
  protected void OnDestroy () {
    Super.ondestroy ();
    Unregisterreceiver (Mbroadcastreceiver);
  }


Note: In all of the design related to the observer pattern in Android, once the register is involved, it must be unregister at the appropriate time. Therefore, the above example requires Unregisterreceiver (Mbroadcastreceiver) in the 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 and broadcast type

Often say "send a broadcast" and "receive", on the surface of the broadcast as an entity in the Android broadcast mechanism, in fact, the entity itself is not the so-called "broadcast" object, but with "intention" (Intent) to express. Defining the process of defining a broadcast is actually the corresponding broadcast "intent" process, and then sending this "intent" through the broadcast sender. When received by the corresponding Broadcastreceiver, the OnReceive () function is recalled.

The next snippet of code shows the process of defining a common broadcast, and sending it out concurrently. of which Setaction (..) Corresponds to the action in the Intentfilter in Broadcastreceiver.

Intent Intent = new Intent ();
Intent.setaction (broadcast_action);
Intent.putextra ("name", "Qqyumidi");
Sendbroadcast (Intent);

Depending on how your broadcast is sent, you can divide it 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, and the corresponding sticky ordered broadcast, also deprecated)
5.Local Broadcast:app in-app broadcast

The following is a summary of the various types of delivery methods and their characteristics.
1). Normal broadcast: General broadcast
The general broadcast is defined here as: the developer's own definition of 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).
Regular broadcasts are received by a corresponding interest (Intent-filter match) that is registered, and the order is unordered. If you have the appropriate permission requirements to send a broadcast, Broadcastreceiver should also have the appropriate permissions if you want to receive this broadcast.

2). System Broadcast: Systems broadcast
The Android system has a number of system broadcasts built into it, as long as it involves the basic operation of the phone, and basically emits a corresponding system broadcast. Such as: Open start, network state changes, photo, screen closed and open, light up and so on. Each system broadcast has a specific intent-filter, including the specific action, which will be received by the corresponding Broadcastreceiver after the system broadcast is issued. System broadcast within the system when a specific event occurs, the system is automatically issued.

3) Ordered broadcast: Ordered broadcast
Orderly broadcast ordered broadcast in the "orderly" is for the broadcast receiver, refers to the broadcast sent out by the Broadcastreceiver in accordance with the sequential received. The process of defining an ordered broadcast is the same as that of a regular broadcast, except that its main mode of transmission becomes: sendorderedbroadcast (Intent, receiverpermission, ...).

For ordered broadcasts, the main features are summarized as follows:
1> A number of currently registered and valid Broadcastreceiver receive ordered broadcasts in sequential order, The order criterion follows: All valid dynamic registers and statically registered Broadcastreceiver in the current system are sorted from large to small according to the priority property values, and dynamic broadcasts are in the front for dynamic broadcast and static broadcasts with the same priority.

2> received Broadcastreceiver can truncate this ordered broadcast so that the following broadcastreceiver no longer receive this broadcast, or you can modify the broadcast. Causes the subsequent broadcastreceiver to receive the broadcast and parse the wrong parameter values. Of course, in general, such operations are not recommended for ordered broadcasts, 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 deprecated).

Since already deprecated, here does not do more summary.

5 Local Broadcast:app applications (app apps for apps in App domain)

As explained above, the broadcast in Android can communicate across the process or even across the app, and the registration is exported for Intent-filter, the default value is true, and the potential security risks are as follows:

1. Other apps may target broadcasts that match the current app Intent-filter, resulting in the current app receiving broadcasts and processing;

2. Other apps can register with the current app Intent-filter to receive broadcasts and get broadcast specific information.

In either case, these security risks do exist. As a result, the most common security-enhancing scenarios are:

1. For the same app to send and receive broadcasts, the exported property is artificially set to false, so that the radio not issued within the app is not received;

2. In the broadcast sending and receiving, all increases the corresponding permission, uses for the authority authentication;

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 sink that matches the app in this package.

App Radio can be understood as a form of local broadcasting, where both the sender and receiver of the broadcast belong to an app. In actual business requirements, app broadcasts may indeed need to be used. At the same time, it is more about security issues in the Android broadcast system than in the form of global broadcasts when using an in-app broadcast.

In comparison to Global broadcasting, the advantage of app application is embodied in:

1. Higher security;

2. More efficient.

To this end, the Android V4 Compatibility Pack provides a packaged Localbroadcastmanager class for unified handling of broadcast problems in app applications, almost the same way as the usual global broadcasts, just registering/ The keynote context is changed to a single instance of Localbroadcastmanager by canceling the registration broadcast receiver and sending the broadcast.

The code snippet is as follows:

Registerreceiver (Mbroadcastreceiver, intentfilter);
Register an application for an internal broadcast receiver
Localbroadcastmanager = localbroadcastmanager.getinstance (this);
Localbroadcastmanager.registerreceiver (Mbroadcastreceiver, intentfilter);
    
Unregisterreceiver (mbroadcastreceiver);
Unregister the application of the internal broadcast receiver
Localbroadcastmanager.unregisterreceiver (mbroadcastreceiver);

Intent Intent = new Intent ();
Intent.setaction (broadcast_action);
Intent.putextra ("name", "Qqyumidi");
Sendbroadcast (intent);
Send application
localbroadcastmanager.sendbroadcast (intent);

4. Different registration mode of broadcast receiver callback OnReceive (context, intent) in the context of specific types

1. For static registration of the Contextreceiver, callback OnReceive (context, intent) in a context specifically refers to the receiverrestrictedcontext;

2. For global broadcast dynamic registration of Contextreceiver, callback OnReceive (context, intent) in a context that refers to the activity of the State;

3. For contextreceiver through Localbroadcastmanager dynamic registration, the context in callback OnReceive (context, intent) refers specifically to the application.

Note: For applications that are sent in Localbroadcastmanager mode, Only contextreceiver that are dynamically registered through Localbroadcastmanager can receive (static registration or otherwise dynamically registered Contextreceiver is not received).

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

1). Android5.0/api level 21 begins the expiration of sticky broadcasts and ordered sticky broadcasts and is no longer recommended for use;

2). " Static registered broadcast receivers can still be received, even if the app has exited, with a corresponding broadcast, but this description may not be valid since Android 3.1.

The Android 3.1 start system adds parameters to the intent-related flag, respectively, Flag_include_stopped_packages and Flag_exclude_stopped_packages.
Flag_include_stopped_packages: Contains the stopped package (stop: The process where the package is already exited)
Flag_exclude_stopped_packages: Does not contain a package that has been stopped

The main reasons are as follows:

Since Android3.1 began, the system itself has increased the tracking of whether all apps are currently running. When broadcasting is sent, no matter what broadcast type, the system defaults directly to adding a value of flag_exclude_stopped_packages flag, resulting in even a statically registered broadcast receiver that cannot receive broadcasts for the app whose process has exited.

For more details, take the official Android document: Http://developer.android.com/about/versions/android-3.1.html

As a result, for system broadcasts, the intent flag value cannot be changed because it is emitted directly from within the system, so the 3.1 starts broadcasting broadcastreceiver for statically registered receive systems and cannot receive broadcasts if the app process has exited.

But for a custom broadcast, you can copy this flag for Flag_include_stopped_packages, allowing statically registered Broadcastreceiver to receive broadcasts even if the app process has exited, and will start the application process. But this time the broadcastreceiver is new.
Intent Intent = new Intent ();
Intent.setaction (broadcast_action);
Intent.addflags (intent.flag_include_stopped_packages);
Intent.putextra ("name", "Qqyumidi");
Sendbroadcast (Intent);

Note 1: for dynamically registered types of broadcastreceiver, this is not affected by this change because this registration and cancellation is actually performed in other components, such as activity.

NOTE 2: before 3.1, it is believed that many apps may monitor various system broadcasts through static registration, in order to do some business processing (such as Instant app has exited, can still receive, can start service, etc.). , after 3.1, static registration to accept the change of broadcast mode, will directly lead to such a scheme is no longer feasible. As a result, setting up the service and the app itself into different processes has become a viable alternative to achieving such requirements.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.