Android Learning Note (13)--Broadcasting mechanism

Source: Internet
Author: User

This series is the "first line of Android Code" Learning notes, if there are errors and omissions, please correct me!

Every app in Android can register a broadcast of interest, so the program will only receive the broadcast content that it cares about, either from the system or from other applications. Android provides a complete set of APIs that allow applications to freely send and receive broadcasts.

I. Type of broadcast:

Broadcast in Android can be divided into two types, standard broadcast and ordered broadcast.

1) standard broadcast (normal broadcasts) is a completely asynchronous broadcast, and after the broadcast, all broadcast receivers will receive the broadcast message almost at the same time, so there is no sequencing between them. This kind of broadcast is more efficient, but it also means that it cannot be truncated.

2) ordered broadcast (Ordered broadcasts) is a synchronous broadcast, after the broadcast, only one broadcast receiver will be able to receive this broadcast message at the same time, and when the logic in this broadcast receiver is completed, the broadcast will continue to pass. So at this time the broadcast receiver is in order, the priority of the broadcast receiver can receive a broadcast message, and the front of the broadcast receiver can also truncate the broadcast is being delivered, so that the subsequent broadcast receivers will not be able to receive broadcast messages.

Second, the reception system broadcast:

Android has a lot of system-level broadcasts built in, and we can listen to these broadcasts in the application to get status information for various systems. For example, when the cell phone is turned on, a broadcast will be issued, and the battery's power will be changed to a
Broadcast, time or timezone changes will also issue a broadcast, and so on. If you want to receive these broadcasts, you need to use a broadcast receiver. Broadcast receivers are free to register their own broadcasts of interest, so that when a corresponding broadcast is issued, the broadcast receiver is able to receive the broadcast and process the corresponding logic internally. There are generally two ways of registering a broadcast, registering it in code and registering it in Androidmanifest.xml, where the former is also known as dynamic registration, which is also known as static registration.

1) Dynamic registration:
We use dynamic registration to implement a feature that reminds the user that the network is turned on and the code is as follows:

1  Public classMainactivity extends Appcompatactivity {2 3     PrivateIntentfilter Intentfilter;4     Privatenetworkchangereceiver Networkchangereceiver;5 @Override6     protected voidonCreate (Bundle savedinstancestate) {7 super.oncreate (savedinstancestate);8 Setcontentview (r.layout.activity_main);9Intentfilter =NewIntentfilter ();TenIntentfilter.addaction ("Android.net.conn.CONNECTIVITY_CHANGE"); OneNetworkchangereceiver =Newnetworkchangereceiver (); A registerreceiver (Networkchangereceiver, intentfilter); -     } - @Override the     protected voidOnDestroy () { - Super.ondestroy (); - Unregisterreceiver (networkchangereceiver); -     } +     classNetworkchangereceiver extends Broadcastreceiver { - @Override +          Public voidOnReceive (Context context, Intent Intent) { AConnectivitymanager ConnectionManager =(Connectivitymanager) at Getsystemservice (context.connectivity_service); -Networkinfo Networkinfo =connectionmanager.getactivenetworkinfo (); -             if(Networkinfo! =NULL&&networkinfo.isavailable ()) { -Toast.maketext (Context,"Network is available", - toast.length_short). Show (); -}Else { inToast.maketext (Context,"Network is unavailable", - toast.length_short). Show (); to             } +         } -     } the}
View Code

We define an inner class networkchangereceiver in Mainactivity, which is inherited from Broadcastreceiver and overrides the OnReceive () method of the parent class. This allows the OnReceive () method to be executed whenever the network state changes. In the OnReceive () method, the first instance of the Connectivitymanager is obtained through the Getsystemservice () method, which is a system service class dedicated to managing network connections. Then call its Getactivenetworkinfo () method to get the Networkinfo instance, and then call Networkinfo's IsAvailable () method, you can determine whether there is currently a network, and finally we still through The way the toast is prompted for the user.

Then observing the OnCreate () method, we first created an instance of Intentfilter and added an action with a value of Android.net.conn.CONNECTIVITY_CHANGE, and when the network state changed, The system sends out a broadcast with a value of Android.net.conn.CONNECTIVITY_CHANGE, which means that our broadcast receivers want to listen to what broadcasts, and add the corresponding action here. Next, a Networkchangereceiver instance is created, and then the Registerreceiver () method is called to register, Networkchangereceiver instances and Intentfilter instances are passed in. So Networkchangereceiver will receive all the values of Android.net.conn.CONNECTIVITY_CHANGE broadcast, but also to achieve the ability to listen to network changes.

Finally, remember that the dynamically registered broadcast receivers must be unregistered only, here we are in the OnDestroy () method by calling the Unregisterreceiver () method to achieve.

In addition, there is a very important point to note that the network state of the query system here is the need to declare permissions, or the program will directly crash, the statement only if the following statements in the manifest file:

1 <  android:name= "Android.permission.ACCESS_NETWORK_STATE"/>

The effect is as follows:

  

  2) Static registration:

Dynamically registered broadcast receivers have the freedom to control registration and logoff and have a great advantage in terms of flexibility, but it has to be done before the program starts to receive the broadcast, and if we want the program to turn it on? At this point we can use static registration:

(1) first create a new bootcompletereceiver Inherited from Broadcastreceiver, the code is as follows:

 1  public  class  bootcompletereceiver   Broadcastreceiver { 2  Span style= "color: #000000;" > @Override  3  public  void   OnReceive (context context, Intent Intent) { 4  toast.maketext (context, "Boot complete" , Toast.length_long). Show ();  5   6  }

In the Onrecieve () method we simply pop up a text.

(2) in the manifest file to obtain permission and declare the broadcast, the code is as follows:

1 <  android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/>

Monitoring System on the radio is also required to declare permissions, we use the <uses-permission> tag and added a Android.permission.RECEIVE_BOOT_COMPLETED permission. We then insert the following code under the application tag:

1 <receiverAndroid:name=". Bootcompletereceiver " >2     <Intent-filter>3           <ActionAndroid:name= "Android.intent.action.BOOT_COMPLETED" />4     </Intent-filter>5 </receiver>

All broadcast receivers that are statically registered are registered on the label <receiver>. Use Android:name to specify which broadcast receiver to register, and then add the broadcast you want to receive in the <intent-filter> tab. As the Android system launches, a broadcast with a value of Android.intent.action.BOOT_COMPLETED is issued, so we have added the appropriate action here.

After restarting the phone, the program pops up the text on the screen: boot complete.

End.

Android Learning Note (13)--Broadcasting mechanism

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.