Broadcastreceiver introduction of Android four basic components

Source: Internet
Author: User

This paper mainly introduces Broadcastreceiver concept, use, life cycle, security, classification, special broadcastreceiver (local, sticky, orderly, sticky and orderly broadcasting). example code see BROADCASTRECEIVERDEMO, example apk see:trineaandroiddemo.apk.

1. Concept introduction and the difference between the two ways of registration

Broadcastreceiver as one of the four components of Android, unlike activity, there is no interface to display. Broadcastreceiver consists of two concepts, the broadcast sender and the broadcast receiver (receiver), where the broadcast actually refers to the intent, the program can send itself to receive the broadcast itself, or accept the broadcast of the system or other applications or send broadcasts to other applications.

The sender can send broadcasts via a similar context.sendbroadcast interface, the recipient is dynamically registered via Context.registerreceiver () or in the Androidmanifest.xml file via <receiver> label static registration, after the registration is completed, when the sender sends a broadcast, the system will send the broadcast (Intent) and all the registered eligible recipients (receiver) in the system to match the Intentfilter, If the match succeeds then the corresponding receiver's onreceive function is executed , and the matching rules are found in the matching rules of intent and intentfilter.

The differences between registerreceiver dynamic registration and statically registering broadcasts via <receiver> tags are as follows:

A. Calls to Bindservice ,<receiver> registered broadcasts that do not exist at the end of the onreceive, so it is not possible to pass the result asynchronously to itself. such as Bindservice and can only use StartService, if you want to interact with the service can use Peekservice.

B. Manual control . Registerreceiver for dynamic registration, you can manually register or unregister;<receiver> label for static registration, by the system when the automatic scanning registration, so can not manually control, power-on has been running.

C. Resource consumption is different . Registerreceiver can be controlled manually, so proper registration and cancellation can save system resources,<receiver> label system has been in effect since boot.

D. The validity period is different . Broadcastreceiver registered with Registerreceiver is "destroyed" by the context object to which it was registered or called Unregisterreceiver method, and through <receiver > tag Registration broadcastreceiver is valid as long as the application has not been deleted.

E. The invocation license for the Registerreceiver function is different . Broadcastreceiver registered by Registerreceiver can call the Registerreceiver function of a context again in its onreceive function, and by <receiver> The broadcastreceiver of the label registration does not allow the Registerreceiver function of a context to be called again.

F. Different usage conditions . broadcasts that you send and receive can be registered through Registerreceiver, and the reception of the system's popular broadcasts is usually registered with the <receiver> tag.

2. Use Example

Broadcastreceiverdemo
PublicClass BroadcastreceiverdemoExtendsActivity {PrivateFinalstatic String Action_send = "Com.trinea.android.demo.BroadcastReceiverDemo.sendBroadcast";PrivateFinalstatic String Msg_key = "MSG";PrivateMybroadcastreceiver receiver;PrivateButton sendbtn; @OverridePublicvoidOnCreate (Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.broadcast_receiver_demo); Receiver =NewMybroadcastreceiver (); SENDBTN =(Button) Findviewbyid (r.id.sendbroadcast); Sendbtn.setonclicklistener (NewOnclicklistener () {@OverridePublicvoidOnClick (View v) {sendbtn.settext ("in Send"); Sendbtn.setclickable (False); Intent i =NewIntent (Action_send); I.putextra (Msg_key, "The good sound is starting soon.")); Sendbroadcast (i); } }); } @OverridePublicvoidOnPause () {Super. OnPause (); Unregisterreceiver (receiver); } @OverridePublicvoid Onresume () {super .onresume (); Registerreceiver (receiver, new Intentfilter (action_send)); } public class mybroadcastreceiver extends Broadcastreceiver {@Override public void OnReceive (context context, Intent Intent) {sendbtn.settext ("Send broadcast" ); Sendbtn.setclickable (true

The content of R.layout.broadcast_receiver_demo is a simple button with ID sendbroadcast

From the code above, we can see

A. The new broadcastreceiver only needs to inherit Broadcastreceiver and rewrite the Onreceiver function, plus its own processing logic.

B. Registration of broadcasts through the Registerreceiver, cancellation of the registration of broadcasts through Unregisterreceiver, broadcast by Sendbroadcast.

Registration and de-registration broadcasts in the Onresume and OnPause functions can effectively save system consumption. If you want the broadcast to continue running, you can register in the activity's OnCreate function and unregister in the Ondestrory function.

The mybroadcastreceiver can also be registered statically in the Androidmanifest.xml file, so the program is installed and running. For example, if you want to receive a message when it arrives, the following:

<Android:name= "Mybroadcastreceiver">    <intent-filter<android: Name</intent-filter></receiver>      

3. Life cycle

Broadcastreceiver the end of the life cycle after the execution of the OnReceive function , it is not appropriate to do a bind service operation in OnReceive, and if a process contains only that broadcastreceiver, The priority will be reduced to possibly be reclaimed by the system, so it is not appropriate to do some asynchronous operations in Broadcastreceiver , such as the new thread to download data, Broadcastreceiver may end after the asynchronous operation is completed before the system kill.

Also, since the OnReceive function of the ANR limit broadcastreceiver must be completed within 10 seconds, and OnReceive is executed in the main thread by default, it is not suitable for time-consuming operations in Broadcastreceiver , the time-consuming operation needs to be handed over to service processing, such as network or database time-consuming Operations, dialog box display (because the real time may timeout, with notification instead).

4. Security

Broadcastreceiver is designed to be globally considered to facilitate communication between applications and systems, applications, and applications, so broadcastreceiver is a security issue for a single application, and the corresponding problems and solutions are as follows:

A, when the application sends a broadcast, the system will match the sent intent with the intentfilter of all registered Broadcastreceiver in the system, and execute the corresponding onreceive function if the match succeeds. An interface similar to Sendbroadcast (Intent, String) can be used to specify the permission that the receiver must have when sending broadcasts. or set a broadcast through Intent.setpackage is only valid for a program.

B. When an application registers for a broadcast, even if Intentfilter is set up, it will receive a broadcast from another application to match the judgment. For dynamically registered broadcasts can be via interfaces like Registerreceiver (Broadcastreceiver, Intentfilter, String, Android.os.Handler) Specifies the permission that the sender must have, and for statically registered broadcasts, the android:exported= "false" property indicates that the recipient is unavailable to the external application, that is, the broadcast from outside is not accepted.

C. The above two problems can be solved by Localbroadcastmanager, Localbroadcastmanager will only limit the broadcast to the current application, see the following 6 special Broadcastreceiver in the introduction

D. Using Android:protectionlevel

5. Classification

Broadcastreceiver can be divided into ordinary and orderly two, the following 6 special Broadcastreceiver introduced some other kinds.

Broadcasts sent through Context.sendbroadcast are ordinary broadcasts, and the order in which the ordinary broadcast receiver receives it is uncertain, so that the receiver cannot use the results of other recipients ' processing to stop it.

Broadcasts sent through Context.sendorderedbroadcast are ordered broadcasts, unlike ordinary broadcasts in which the receiver is ordered to receive broadcasts and can modify the broadcast or cancel the broadcast down . The system determines which recipient receives it first based on the order of priority defined by the receiver, and the receiver can pass the result to a low-priority recipient after processing to stop the broadcast so that other low-priority recipients cannot receive it. The priority is defined by the Android:priority attribute, the higher the value, the higher the priority, the value range: 1000 to 1000, although the API documentation describes the broadcast that is sent to Sendbroadcast is not valid, but my test is also valid, Recipients of the same priority receive the broadcast in a random order. The Android system receives the text message, the broadcast which sends after receives the telephone is the orderly broadcast , therefore may carry on the text message or the telephone interception, namely cancels the broadcast.

PS: Ordered broadcasts can be canceled in the OnReceive function via the broadcastreceiver Abortbroadcast interface (this interface is not valid for sendbroadcast sending broadcasts). Via Interface Sendorderedbroadcast (Intent, String, Broadcastreceiver, Android.os.Handler, int, string, Bundle) Sent broadcasts even if the broadcast is canceled by a high-priority broadcast, the broadcastreceiver specified in the interface parameters can still receive the broadcast after the other recipients have finished processing. By broadcastreceiver the Getresultextras interface to obtain the results of the bundle and then through the bundle of putstring and GetString methods to modify or retrieve data, you can see the example code at the end of this article.

6, the special Broadcastreceiver

A. Localbroadcastmanager Local broadcast

Android introduced Localbroadcastmanager to address some of the security issues described in section 4,Localbroadcastmanager In addition to resolving broadcastreceiver inter-process security issues, Compared to the broadcastreceiver of the context operation, it also has higher operational efficiency.

Using Localbroadcastmanager requires the introduction of the Android support Library, and how to introduce the Add support package.

Local broadcasts send broadcasts through the localbroadcastmanager.getinstance (context) Sendbroadcast (intent), Localbroadcastmanager.getinstance ( context). Registerreceiver Registration Service, via Localbroadcastmanager.getinstance (context). Unregisterreceiver Unregister service, other with general broadcast.

B. Sticky broadcast sticky broadcast

If the sender sends a broadcast, and the receiver registers his receiver after the broadcast is sent, the receiver cannot receive the broadcast, and the Stickybroadcast is introduced for Android. The broadcast (Intent) that was just sent is saved after the broadcast is sent, so that the receiver can continue to use the broadcast just after registering receiver. If multiple sticky broadcasts of the same action are sent before the recipient registration is complete, only one broadcast of the action is received after the registration is completed, and the message content is the last broadcast content. changes in System network status the broadcast that is sent is the sticky broadcast.

Sticky broadcasts are sent through the context's Sendstickybroadcast (Intent) interface, which requires adding permissions <uses-permission android:name= " Android.permission.BROADCAST_STICKY "/>

Cached sticky broadcasts can also be removed through the removestickybroadcast (Intent Intent) interface of the context.

C. Orderedbroadcastreceiver Orderly Broadcasting

This has been introduced in the 5 classification, the recipient ordered to receive the broadcast and can modify the broadcast results or cancel the broadcast, through the context of the Sendorderedbroadcast interface sent

D. stickyorderedbroadcast Sticky and orderly broadcasting

This is a combination of sticky broadcasts and ordered broadcasts, sent through the Sendstickyorderedbroadcast interface of the context.

Various broadcast Operation demo sample code see Broadcastreceiverdemo, due to the local broadcast support library temporarily download, not including local broadcast, the local broadcast operation between the above described.

Note the Androidmanifest file needs to add the sticky broadcast operation permission <uses-permission android:name= "Android.permission.BROADCAST_STICKY"/>

Reference:

Http://developer.android.com/reference/android/content/BroadcastReceiver.html

Original address: http://www.cnblogs.com/trinea/archive/2012/11/09/2763182.html

Broadcastreceiver introduction of Android four basic components

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.