Android Summary series: Android broadcast mechanism

Source: Internet
Author: User
Tags variable scope eventbus

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 Registration Type
Broadcastreceiver can be divided into two types of registration: Static registration and dynamic registration.
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 accept the broadcast of other apps;
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;
Android:process the process where the 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 will no longer be established since Android 3.1, This is also illustrated in the 3.1 copy of the official Android document: Http://developer.android.com/about/versions/android-3.1.html#launchcontrols. Since Android3.1, the system itself has increased the tracking of whether all apps are currently running. Android added two intent flags,flag_include_stopped_packages and Flag_exclude_stopped_packages,flag_include_ when sending a broadcast Although Stopped_packages is the default value, when the system sends a broadcast, the flag_exclude_stopped_packages is added directly, resulting in even a statically registered broadcast receiver, which is also unable to receive broadcasts for apps that have exited the process.

Note: 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.

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:

1 registerreceiver (broadcastreceiver receiver, intentfilter filter)
2 registerreceiver (broadcastreceiver receiver, Intentfilter filter, String broadcastpermission, Handler Scheduler

A typical example is as follows:

1  Public classMainactivityextendsActivity {2      Public Static FinalString broadcast_action = "Com.example.corn";3     Privatebroadcastreceiver Mbroadcastreceiver;4 5 @Override6     protected voidonCreate (Bundle savedinstancestate) {7         Super. OnCreate (savedinstancestate);8 Setcontentview (r.layout.activity_main);9 TenMbroadcastreceiver =Newmybroadcastreceiver (); OneIntentfilter Intentfilter =NewIntentfilter (); A intentfilter.addaction (broadcast_action); - registerreceiver (Mbroadcastreceiver, intentfilter); -     } the      - @Override -     protected voidOnDestroy () { -         Super. OnDestroy (); + Unregisterreceiver (mbroadcastreceiver); -     } +  A}

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.

3. Broadcast transmission and broadcast type

1) System broadcast and application broadcast (custom 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 action, after the system broadcast is issued, all of the current unfinished app processes in the system can receive this system broadcast as long as the corresponding Broadcastreceiver is registered.

The process of defining the definition of a broadcast is actually the process of defining the "intent" of the broadcast, and then sending the "intent" through the broadcast sender. Whether it is a system broadcast or a custom broadcast, the corresponding Broadcastreceiver receives a callback to the OnReceive () function.

The next snippet shows a custom 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);

The following shows the message communication within the same component inside the same app (the same thread-ui thread, for convenience, a straightforward example, as described in the previous analysis, where the broadcast mechanism is generally impossible for such scenarios to be used in real-world requirements coding)

1  Public classMainactivityextendsActivity {2      Public Static FinalString broadcast_action = "Com.example.corn";3     Privatebroadcastreceiver Mbroadcastreceiver;4 5 @Override6     protected voidonCreate (Bundle savedinstancestate) {7         Super. OnCreate (savedinstancestate);8 Setcontentview (r.layout.activity_main);9 TenMbroadcastreceiver =Newmybroadcastreceiver (); OneIntentfilter Intentfilter =NewIntentfilter (); A intentfilter.addaction (broadcast_action); - registerreceiver (Mbroadcastreceiver, intentfilter); -     } the  - @Override -     protected voidOnresume () { -         Super. Onresume (); +         NewHandler (). postdelayed (NewRunnable () { - @Override +              Public voidrun () { AIntent Intent =NewIntent (); at intent.setaction (broadcast_action); -Intent.putextra ("name", "Qqyumidi"); - Sendbroadcast (intent); -             } -}, 3 * 1000); -  in     } -  to @Override +     protected voidOnDestroy () { -         Super. OnDestroy (); the Unregisterreceiver (mbroadcastreceiver); *     } $ }Panax Notoginseng  -  Public classMybroadcastreceiverextendsBroadcastreceiver { the      Public Static FinalString TAG = "Mybroadcastreceiver"; +  A @Override the      Public voidOnReceive (Context context, Intent Intent) { +LOG.W (TAG, "intent:" +intent); -String name = Intent.getstringextra ("name"); $LOG.W (TAG, "Name:" +name); $     } -}

# #输出结果为:

1 w/mybroadcastreceiver (30362): intent:intent {act=com.example.corn flg=0x10 (has extras)}2 W/mybroadcastreceiver (30362): Name:qqyumidi

2)

-------not to be continued.

Android Summary series: Android broadcast mechanism

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.