Original link: http://www.orlion.ga/572/
I. Broadcasting mechanism
Every app in Android can register a broadcast that it's interested in, so the program will only receive the broadcast content that it cares about
May be from the system or from other applications. Android provides a complete set of APIs that allow applications to freely send and receive broadcasts. The way to send broadcasts requires the help of intent. The method of receiving the broadcast needs to introduce a new concept, the broadcast receiver (broadcast receiver)
There are two types of broadcasts:
-
Standard broadcast: A completely asynchronous broadcast in which all broadcast receivers receive broadcasts almost at the same time after the broadcast is issued
-
Orderly Broadcasting: A synchronous broadcast in which only one broadcast can receive this message at the same time, and the broadcast will continue to propagate only after the logic in the broadcast receiver has been processed. So at this point the broadcast is sequential, the priority of the broadcast receiver can be broadcast first, and the front of the broadcast receiver can truncate the broadcast is being transmitted, so that the back of the broadcast receiver will not be able to receive the broadcast
Second, 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 phone is turned on, a broadcast will be issued, the battery power will be issued a broadcast, time or timezone changes will be issued a broadcast and so on. If you want to receive these broadcasts, you need to use a broadcast receiver.
1, dynamic registration monitoring network changes
There are generally two ways to register a broadcast, register it in code (dynamic registration) and register it in Androidmanifest.xml (static registration)
How do I create a broadcast receiver? Just create a class that inherits from Broadcastreceiver and overrides the OnReceive () method of the parent class so that when there is a broadcast, the OnReceive () method executes, and the specific logic is executed in this code.
A program that listens to network changes is written by dynamic registration. Create a Broadcastdemo project and modify the Mainactivity code:
package ga.orlion.broadcastdemo;import android.app.activity;import android.content.broadcastreceiver;import android.content.context;import android.content.intent; import android.content.intentfilter;import android.net.connectivitymanager;import android.net.networkinfo;import android.os.bundle;import android.widget.toast;public class mainactivity extends activity {private intentfilter intentfilter;private networkchangereceiver networkchangereceiver; @Overrideprotected void oncreate (bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Intentfilter = new intentfilter (); Intentfilter.addaction ("Android.net.conn.CONNECTIVITY_CHANGE" ); Networkchangereceiver = new networkchangereceiver (); Registerreceiver (networkChangeReceiver , intentfilter);} @Overrideprotected void ondestroy () {suPer.ondestroy (); Unregisterreceiver (networkchangereceiver);} class networkchangereceiver extends broadcastreceiver {@Overridepublic void OnReceive (context context, intent intent) {connectivitymanager connectionmanager = (Connectivitymanager) getsystemservice (Context.connectivity_service); Networkinfo networkinfo = connectionmanager.getactivenetworkinfo ();if (networkInfo != null && networkinfo.isavailable ()) {toast.maketext (context , "Network is available " , toast.length_short). Show ();} else {toast.maketext (context , "network is unavailable" , Toast.length_short). Show ();}}}
As you can see, 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. Then observe the OnCreate () method, first we create an instance of Intentfilter, and add an action with a value of Android.net.conn.CONNECTIVITY_CHANGE, why add this value? Because when the network state changes, the system emits a broadcast with a value of Android.net.conn.CONNECTIVITY_CHANGE, which means that our broadcast receivers want to listen to what the broadcast is, 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 implement the
In addition, there is a very important point to note that the Android system in order to ensure the security of the application, if the program needs to access some of the critical information of the system, you must declare the permissions in the configuration file, or the program will crash directly, For example, the network status of the query system is required to declare permissions. Open the Androidmanifest.xml file, add the following permissions to query the system network status:
2, static registration to achieve boot start
Dynamic registration is very flexible, but it must be started before the program can accept broadcasts, and if you want the program to accept broadcasts without booting, you need to use a static registration method.
We are ready to let the program receive a start-up broadcast, when the broadcast can be received in the OnReceive () method to execute the corresponding logic, so as to achieve the function of start-up, a new bootcompletereceiver inherited from Broadcastreceiver, Code:
Package Ga.orlion.broadcastdemo;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.widget.toast;public class Bootcompletereceiver extends BroadcastReceiver {@ overridepublic void OnReceive (context context, Intent Intent) {toast.maketext (context, "Boot complete", toast.length_ Short). Show ();}}
There is no longer a way to define the broadcast sink using an inner class, because you will need to register the class in Androidmanifest.xml. Modify Androidmanifest.xml:
<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http// Schemas.android.com/apk/res/android " package=" Ga.orlion.broadcastdemo " android:versioncode= "1" android:versionname= "1.0" > <uses-sdk android:minsdkversion= " " android:targetsdkversion= " /> <" Uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/><uses-permission Android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/> <application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@ String/app_name "&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; android:theme= "@style/apptheme" > < Activity android:name= ". Mainactivity " android:label=" @string/ App_name " > <intent-filter > <action android:name= "Android.intent.action.MAIN" /> <category android:name= " Android.intent.category.LAUNCHER " /> </intent-filter> </activity> &nbSp; <receiver android:name= ". Bootcompletereceiver "> < intent-filter> <action android:name= "Android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </application></manifest>
You need to declare permissions.
Third, send a custom broadcast
1. Send standard broadcast
First define a broadcast receiver to receive our broadcasts, create mybroadcastreceiver inherit from Broadcastreceiver, code:
Package Ga.orlion.broadcastdemo;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.widget.toast;public class Mybroadcastreceiver extends BroadcastReceiver {@ overridepublic void OnReceive (context context, Intent Intent) {toast.maketext (Context, "received broadcast", Toast.length_short). Show ();}}
Register in Androidmanifest.xml:
<receiver android:name= ". Mybroadcastreceiver "> <intent-filter> <action android:name=" Ga.orlion.broadcastdemo. My_broadcast "/> </intent-filter> </receiver>
Then modify the mainactivity:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View v) {Intent Intent = new Intent ("Ga.orlion.broadcastdemo.MY_BROADCAST"); Sendbroadcast ( Intent);}});}
Send a broadcast when you click the button.
2. Send an orderly broadcast
Broadcast is a cross-process communication, so our applications emit broadcasts that other applications should also be able to receive.
Now we're trying to send an ordered broadcast
Modify Mainactivity:
@Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View v) {Intent Intent = new Intent ("Ga.orlion.broadcastdemo.MY_BROADCAST"); Sendorderedbroadcast (intent, NULL);}});}
As you can see, sending an ordered broadcast requires only one line of code to change and the Sendbroadcast () method is changed to the Sendorderedbroadcast () method. The Sendorderedbroadcast () method receives two parameters, the first parameter is still intent, and the second parameter is a permission-related string, where null is passed.
Next, set the order of the broadcast receivers in the configuration file, Androidmanifest.xml:
<receiver android:name= ". Mybroadcastreceiver "> <intent-filter android:priority=" "> <action android:name=" G A.orlion.broadcastdemo.my_broadcast "/> </intent-filter> </receiver>
Mybroadcastreceiver can choose whether to allow the broadcast to continue to pass. To modify the code in Mybroadcastreceiver
Package Ga.orlion.broadcastdemo;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.widget.toast;public class Mybroadcastreceiver extends BroadcastReceiver {@ overridepublic void OnReceive (context context, Intent Intent) {toast.maketext (Context, "received broadcast", Toast.length_short). Show (); Abortbroadcast ();}}
If the Abortbroadcast () method is called in the OnReceive () method, it means that the broadcast is truncated and subsequent broadcast receivers will no longer be able to receive the broadcast.
Iv. use of local broadcasts
The broadcasts we send and receive are all part of the system global broadcast, that is, broadcasts that are sent can be received by any other application, and we can receive broadcasts from any other application. This can easily lead to security issues, in order to be able to easily solve the broadcast security issues, Android introduced a set of local broadcast mechanism, the use of this mechanism issued by the broadcast can only be transmitted within the application, and broadcast receivers can only receive from the application
Broadcast by the program. The use of local broadcasts is not complicated, mainly by using a localbroadcastmanager for broadcasting
Management, and provides methods for sending broadcasts and registering broadcast receivers.
Modify Mainactivity:
package ga.orlion.broadcastdemo;import android.app.activity;import android.content.broadcastreceiver;import android.content.context;import android.content.intent; import android.content.intentfilter;import android.os.bundle;import android.support.v4.content.localbroadcastmanager;import android.view.view;import android.widget.button;import android.widget.toast;public class mainactivity extends activity {private intentfilter intentfilter;private localreceiver localreceiver; private localbroadcastmanager localbroadcastmanager; @Overrideprotected void oncreate ( bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main ); Localbroadcastmanager = localbroadcastmanager.getinstance (this); button button = (Button) findviewbyid (R.id.button); Button.setonclicklistener (new View.onclicklistener () {@Overridepublic void onclick (view v) {intent intent = new intent (" Ga.orlion.broadcastdemo.LOCAL_BROADCAST "); Localbroadcastmanager.sendbroadcast (intent);}); Intentfilter = new intentfilter (); Intentfilter.addaction ("Ga.orlion.broadcastdemo.LOCAL_ Broadcast "); Localreceiver = new localreceiver (); Localbroadcastmanager.registerreceiver ( Localreceiver, intentfilter);} @Overrideprotected void ondestroy () {super.ondestroy (); localbroadcastmanager.unregisterreceiver (Localreceiver);} class localreceiver extends broadcastreceiver {@Overridepublic void onreceive ( context context, intent intent) {toast.maketext (context, "received local broadcast", Toast.LENGTH _short). Show ();}}}
First, an instance of it is obtained by Localbroadcastmanager's getinstance () method, and then the Localbroadcastmanager registerreceiver () is called when registering the broadcast receiver. method, the Localbroadcastmanager sendbroadcast () is called when the broadcast is sent
Method.
Android Primer (eight) broadcast