Android four components of the third (broadcast)

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

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:

1 Registerreceiver (broadcastreceiver receiver, Intentfilter filter) 2 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.

Android four components of the third (broadcast)

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.