"declaration"
Welcome reprint, but please keep the original source of the article →_→
Life One number: http://www.cnblogs.com/smyhvae/
Article Source: http://www.cnblogs.com/smyhvae/p/3960623.html
Contact information: [Email protected]
Body
I. Functions and characteristics of broadcasting
- The life cycle of the broadcast is very short, and the entire process is finished by invoking the object--and implementing onreceive-->. From the complexity of implementation and the amount of code, broadcast is undoubtedly the most mini Android component, the implementation often only a few lines of code. When a broadcast object is constructed, it usually executes only the Broadcastreceiver.onreceive method and ends its life cycle. So sometimes we can think of it as a function or not.
- As with all components, the broadcast object is also constructed in the main thread of the application process, so the broadcast object must be executed synchronously and quickly. It is also not recommended to open a sub-thread inside, because the thread is not finished, and the broadcast object has been executed and destroyed by the system. If you need to complete a more time-consuming task, you should do so by sending Intent to the service.
- Each time the broadcast arrives, the Broadcastreceiver object is recreated, and the OnReceive () method is called, and the object is destroyed when it finishes executing. When the OnReceive () method is not completed within 10 seconds, Android will consider the program unresponsive.
Second, the reception system broadcast:
Broadcast receivers are free to register their own broadcasts of interest, so that when a corresponding broadcast is issued, the broadcast receiver can receive the broadcast and process the corresponding logic internally. There are two ways of registering a broadcast, registering it in code and registering it in a manifest file, which is called dynamic registration, which is called static registration.
1, dynamic registration monitoring network changes:
Create a new project file, first define an inner class networkchangereceiver in Mainactivity, and override the OnReceive () method of the parent class so that the OnReceive () method is executed whenever the network state changes. Here is a text message with a toast hint, with the following code:
Class Networkchangereceiver extends Broadcastreceiver { @Override public void OnReceive (context context, Intent Intent) { Toast.maketext (context, "Network changes", Toast.length_short). Show (); } }
This is followed by dynamic registration in the OnCreate method and then unregister in the OnDestroy method:
1 private intentfilter intentfilter; 2 private Networkchangereceiver networkchangereceiver; 3 4 @Override 5 protected void OnCreate (Bundle savedinstancestate) {6 super.oncreate (savedinstancestate); 7 Setcontentview (R.layout.activity_main); 8 9 //Dynamic registration: Create an instance of Intentfilter, add a broadcast of network changes (function is to filter the components, Get only the required messages) Intentfilter = new Intentfilter (); intentfilter.addaction ("Android.net.conn.CONNECTIVITY_ Change ") //Create an instance of Networkchangereceiver and call the Registerreceiver () method to register the networkchangereceiver = new Networkchangereceiver (); registerreceiver (Networkchangereceiver, intentfilter); you must Remember, or the system will error @Override20 protected void OnDestroy () { Super.ondestroy (); unregisterreceiver (Networkchangereceiver);
The above code is interpreted as follows:
11 Line: Add an action with a value of Android.net.conn.CONNECTIVITY_CHANGE to the intent filter intentfilter. Because whenever the network state changes, a broadcast with a value of Android.net.conn.CONNECTIVITY_CHANG is emitted.
Note: Finally, it is important to remember that dynamically registered broadcast receivers must be unregistered.
Run the program and you're ready.
But just to remind the network change is not enough human, in order to be able to tell the user exactly whether there is a network or no network, we also need to further optimize the above code, modify the code in Networkchangereceiver as follows:
1 class Networkchangereceiver extends Broadcastreceiver {2 3 @Override 4 public void OnReceive ( Context context, Intent Intent) {5 //Through the Getsystemservice () method to get ConnectionManager This system service class, specifically for managing network Connections 6 Connectivitymanager ConnectionManager = (connectivitymanager) getsystemservice (Context.connectivity_service); 7 Networkinfo networkinfo = Connectionmanager.getactivenetworkinfo (); 8 if (networkinfo! = null && Networkinfo.isavailable ()) {9 toast.maketext (context, "Network is available", Toast.length_short). Show (); 10 }else{11 toast.maketext (context, "Network is unavailable", Toast.length_short). Show (); 13 } + } }
The above code explains:
06 Line: In the OnReceive () method, first by means of the Getsystemservice () method to get ConnectionManager This system service class, specifically for the management of network connections.
07 Line: Then call its Getactivenetworkinfo () method can get Networkinfo instance, and then call Networkinfo isavailable () method, you can determine whether there is currently a network, The user is finally prompted with a toast.
In addition, the network status of the query system is required to declare permissions, open the manifest file, add the following permissions:
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
Note: Access http://developer.android.com/reference/android/Manifest.permission.html can view all the rights that are declared on the Android system.
Now run the program and you're ready.
The full version of the above program code is as follows:
View Code
2, static registration to achieve boot:
Dynamic registration is more flexible, but the disadvantage is that the broadcast must be received after the program is started, because the registered logic is written in the OnCreate () method. In order for the program to receive the broadcast without booting, you need to use static registration.
Here we prepare the program to receive a start-up broadcast, when received this broadcast, you can execute the corresponding logic in the OnReceive () method, so as to achieve the function of power-on startup.
Create a new class: Bootcompletereceiver, let him inherit broadcastreceiver, simply toast in the OnReceive () method, the code is as follows:
public class Bootcompletereceiver extends Broadcastreceiver { @Override public void OnReceive (context context, Intent Intent) { Toast.maketext (context, "Boot complete", Toast.length_short). Show (); }}
As you can see, there is no longer a way to define a broadcast sink using an inner class, because we need to register the class name of the broadcast receiver in the manifest file Androidmanifest.xml later.
Then modify the manifest file Androidmanifest.xml with the following code:
1 <uses-sdk 2 android:minsdkversion= "8" 3 android:targetsdkversion= "+"/> 4 <uses-permission Android:name= "Android.permission.ACCESS_NETWORK_STATE"/>5 <uses-permission android:name= "Android.permission.RECEIVE_BOOT_COMPLETED"/>6 7 <application 8 android:allowbackup= "true" 9 android:icon= "@drawable/ic_launcher" and Roid:label= "@string/app_name" one android:theme= "@style/apptheme" >12 <activity13 android: Name= "Com.example.m05_broadcastreceiver01. Mainactivity "android:label=" @string/app_name ">15 <intent-filter>16 &L T;action android:name= "Android.intent.action.MAIN"/>17 <category android:name= "android.intent.ca Tegory. LAUNCHER "/>19 </intent-filter>20 </activity>21<receiver android:name= ". Bootcompletereceiver ">23 <intent-filter >24 <action android:name=" android.intent.a Ction. boot_completed "/>25 </intent-filter>26 </receiver></application>
The code is interpreted as follows:
Finally,<application> the label inside the child tag <receiver>, all of the static registered broadcast receivers are registered here.
22 Rows: Name of the broadcast receiver
24 Line: The broadcast you want to receive. This broadcast, called Android.intent.action.BOOT_COMPLETED, will be issued when the Android system is started.
05 Line: The monitoring system on the broadcast needs to declare permissions.
After running the program, the hand machine restarts, you can receive the broadcast.
Third, send a custom broadcast
1. Send standard broadcast
Create a new project file. Before sending the broadcast, we define a broadcast receiver to receive this broadcast. Therefore, create a new class: Mybroadcastreceiver, let him inherit Broadcastreceiver, the code is as follows:
public class Mybroadcastreceiver extends Broadcastreceiver { @Override public void OnReceive (context context, Intent Intent) { Toast.maketext (context, "received in Mybroadcastreceiver", Toast.length_short). Show (); }}
Here, when Mybroadcastreceiver receives a custom broadcast, it executes the logic in the OnReceive () method and pops up a toast.
Next, to register this broadcast receiver in the manifest file Androidmanifest.xml:
1 <application 2 android:allowbackup= "true" 3 android:icon= "@drawable/ic_launcher" 4 android: Label= "@string/app_name" 5 android:theme= "@style/apptheme" > 6 <activity 7 android:name= " Com.example.m05_broadcastreceiver02. Mainactivity "8 android:label=" @string/app_name "> 9 <intent-filter>10 <action android: Name= "Android.intent.action.MAIN"/>11 <category android:name= "Android.intent.category.LAUNCHER"/ >13 </intent-filter>14 </activity>15 <receiver android:name= ". Mybroadcastreceiver ">17 <intent-filter >18 <action android:name=" com.example.m05_ Broadcastreceiver02. My_broadcast "/>19 </intent-filter>20 </receiver> </application>
Code Explanation:
18 Rows: Let Mybroadcastreceiver receive a value of Om.example.m05_broadcastreceiver02. My_broadcast, so we're going to need to send out a broadcast in a moment.
Immediately, modify the code in the Activity.xml and add a button.
Then, modify the code in the Mainactivity.java to add a listener event for the button: When you click the buttons, the radio is sent
Button button1= (button) Findviewbyid (r.id.button1); Button1.setonclicklistener (New Onclicklistener () { @Override public void OnClick (View v) { =new Intent ("Com.example.m05_broadcastreceiver02. My_broadcast "); Sendbroadcast (intent); } });
Summary: You can see that when you click the button, send Com.example.m05_broadcastreceiver02. My_broadcast this broadcast, so that all can listen to Com.example.m05_broadcastreceiver02. My_broadcast the broadcast receiver will receive the message at the same time , the issue is a standard broadcast, that is, disorderly broadcast. So the next step is to talk about orderly broadcasts.
2. Send an orderly broadcast:
Broadcasting is a way of communicating across processes that other applications can receive. Now let's send an orderly broadcast.
Ordered broadcasts are not only sequential, but the previous broadcasts can also truncate the subsequent broadcasts.
On the basis of 5.3.1 code, the Listener event of the button is modified as follows:
1 button button1= (button) Findviewbyid (R.id.button1); 2 Button1.setonclicklistener (new Onclicklistener () { 3 @Override4 public void OnClick (View v) {5 Intent Intent =new Intent ("com.example.m05_ Broadcastreceiver02. My_broadcast "); 6 sendorderedbroadcast (intent, NULL); 7 }8 });
To modify the 06 lines of code, change the Sendbroadcast () method to the Sendorderedbroadcast () method, the Sendorderedbroadcast () method receives two parameters, the second parameter is a permission-related string, Null can be passed in here.
Immediately thereafter, modify the registration of the broadcast receiver in the manifest file Androidmanifest.xml, setting the priority level:
1 <receiver android:name= ". Mybroadcastreceiver ">2 android:priority=" ">3 <action android:name=" com.example.m05 _broadcastreceiver02. My_broadcast "/>4 </intent-filter>5 </receiver>
The No. 02 line of code is added. As you can see, the broadcast receiver is prioritized by the Android:priority property. This property has a range of 1000 to 1000, and the higher the value, the greater the precedence.
Next, if you want to intercept the broadcast, prevent the broadcast receiver from receiving the broadcast. You can modify the code in the Mybroadcastreceiver:
1 public class Mybroadcastreceiver extends Broadcastreceiver {2 3 @Override4 public void OnReceive (Context Context, Intent Intent) {5 Toast.maketext (Context, "received in Mybroadcastreceiver", Toast.length_short). Show (); 6 Abortbroadcast ()//intercept the broadcast to prevent the subsequent receipt of 7 }8}
The No. 06 line of code is added. If the Abortbroadcast () method is called in the OnReceive () method, it means that the broadcast is intercepted and the subsequent broadcast receivers will no longer be able to receive it.
Special attention:
- The life cycle of the broadcast receiver: The key is the OnReceive () method in Broadcastreceiver, starting with the first line of code in OnReceive () and ending with the last line of code in OnReceive ().
- When a broadcast arrives, what is the most friendly way to remind users? The first way is toast, the second way is notification. Note: Do not use a dialog box to avoid interrupting actions that the user is taking.
Iv. use of local broadcasts:
The broadcasts we send and receive are all global broadcasts, that is, broadcasts that are sent out can be received by any other application, and we can also receive broadcasts from any other application. This will inevitably lead to security problems. Then there is a local broadcast: The broadcast can only be sent and received in this application. This is going to use the Localbroadcastmanager class to manage the broadcast.
We modified the code in 2.1 to dynamically register the broadcast receiver, that is, modify the code in Mainactivity.java as follows:
Package Com.example.broadcasttest;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.view.view.onclicklistener;import Android.widget.button;import Android.widget.toast;public Class Mainactivity extends Activity {private Intentfilter intentfilter;private Localreceiver Localreceiver; PrivateLocalbroadcastmanager Localbroadcastmanager;@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Get an example of it by Localbroadcastmanager's getinstance () methodLocalbroadcastmanager = localbroadcastmanager.getinstance ( this);Button button = (button) Findviewbyid (R.id.button); Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent= new Intent ("Com.example.broadcasttest.LOCAL_BROADCAST"); Localbroadcastmanager.sendbroadcast (intent);//Call the Sendbroadcast () method to send the broadcast} }); Dynamically registering a local broadcast receiver Intentfilter = new Intentfilter ();Intentfilter.addaction ("Com.example.broadcasttest.LOCAL_BROADCAST"); Localreceiver = newLocalreceiver (); Localbroadcastmanager.registerreceiver (Localreceiver, intentfilter);} @Override protected void OnDestroy () {Super.ondestroy ();Localbroadcastmanager.unregisterreceiver (localreceiver);}class Localreceiver extends Broadcastreceiver {@Override public void onreceive (context context, Intent Intent) {Toast.maketext (context, "received local broadcast", Toast.length_short). Show (); } }}
Note: Local broadcasts cannot be received by a static registration method. In fact, it is completely understandable, because static registration is mainly to let the program in the case of non-booting can also receive the broadcast. While sending a local broadcast, our program must have been started, and it is not necessary to use the function of static registration.
V. All kinds of broadcasts:
There are many system-intent.action in Android, we can do many functions by listening to these events.
- Boot:
String boot_completed_action Broadcast: After the system starts. This action is broadcast once (only once). Listening: "Android.intent.action.BOOT_COMPLETED"
- Phone dial-in:
String answer_action Action: Handles incoming calls. Listening: "Android.intent.action.ANSWER"
- Power Change:
String Battery_changed_action Broadcast: The charging state, or the battery's power change. Listening: "Android.intent.action.BATTERY_CHANGED"
- Date changed:
String date_changed_action Broadcast: the date is changed. Listening: "Android.intent.action.DATE_CHANGED"
- To cancel an update download:
String fota_cancel_action Broadcast: Cancels all pending (pending) Update downloads. Listening: "Android.server.checkin.FOTA_CANCEL"
- Update to start the installation:
String fota_ready_action Broadcast: The update has been downloaded to start the installation. Monitor "Android.server.checkin.FOTA_READY"
- Home screen:
String home_category Category: Home screen (activity). The first activity that appears after the device starts. Listening: "Android.intent.category.HOME"
- New applications:
String package_added_action Broadcast: A new application package is installed on the device. Listening: "Android.intent.action.PACKAGE_ADDED"
- To delete an app:
String package_removed_action Broadcast: An application package was deleted on the device. Listening: "Android.intent.action.PACKAGE_REMOVED"
- Screen off:
String screen_off_action Broadcast: The screen is closed. Listening: "Android.intent.action.SCREEN_OFF"
- Screen Open:
String screen_on_action Broadcast: The screen has been opened. Listening: "Android.intent.action.SCREEN_ON"
- Time zone Change:
String timezone_changed_action Broadcast: The time zone has changed. Listening: "Android.intent.action.TIMEZONE_CHANGED"
- Time Change:
String Time_changed_action Broadcast: Time has changed (reset). "Android.intent.action.TIME_SET"
- Time Lapse:
String time_tick_action Broadcast: The current time has changed (normal time passes). "Android.intent.action.TIME_TICK"
- Enter mass storage mode:
String ums_connected_action Broadcast: device enters USB mass storage mode. "Android.intent.action.UMS_CONNECTED"
- To exit the mass storage mode:
String ums_disconnected_action Broadcast: The device exits from USB mass storage mode. "Android.intent.action.UMS_DISCONNECTED"
- Wallpaper changes:
String wallpaper_changed_action Broadcast: The system's wallpaper has changed. "Android.intent.action.WALLPAPER_CHANGED"
- Web search:
String web_search_action Action: Performs a WEB search. "Android.intent.action.WEB_SEARCH"
- Network changes:
String connectivity_change_action Action: Network change. "Android.intent.action.CONNECTIVITY_CHANGE_ACTION"
Vi. Example: use dynamic registration to monitor the phone's power change.
The full version of the code is as follows:
1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2 xmlns:tools= "/http/ Schemas.android.com/tools "3 android:layout_width=" match_parent "4 android:layout_height=" Match_parent "5 android:paddingbottom= "@dimen/activity_vertical_margin" 6 android:paddingleft= "@dimen/activity_ Horizontal_margin "7 android:paddingright=" @dimen/activity_horizontal_margin "8 android:paddingtop=" @ Dimen/activity_vertical_margin "9 tools:context=". Mainactivity ">10 <textview12 android:id=" @+id/textview1 [android:layout_width=] Match_ Parent " android:layout_height=" wrap_content "android:textsize=" 30dp " android:gravity=" Center "/>17 </LinearLayout>
The Activity_main.xml code is as follows:
1 package Com.example.m05_broadcastreceiver02; 2 3 Import android.app.Activity; 4 Import Android.content.BroadcastReceiver; 5 Import Android.content.Context; 6 Import android.content.Intent; 7 Import Android.content.IntentFilter; 8 Import Android.os.Bundle; 9 Import android.widget.textview;10 One public class Mainactivity extends Activity {all private BATTERYBROADCA Streceiver batterybroadcastreceiver;15 Private TextView textview;16 @Override17 protected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); 20 textview= (TextView) Findviewbyid (r.id.textview1); 2122//Dynamic Register monitor Power broadcast receiver Intentfilter intentfilter = new Intentfilter (); intentfilter.addaction ("Android.intent.action.BATTERY_CHANGED"); batterybroadcastreceiver = new Batterybroadcastreceiver ();registerreceiver (Batterybroadcastreceiver, intentfilter);27}28 29//Unregister the broadcast receiver for monitoring power @Override31 protected void OnDestroy () {Super.ondestroy ();Unregisterreceiver (batterybroadcastreceiver);34}35 36//Create a new broadcast receiver, monitor the change of the power of the PNs public class Batterybroadcastreceiver extends Broadcastreceiver {@O Verride39 public void OnReceive (context context, Intent Intent) {40if (intent.getaction (). Equals (intent.action_battery_changed)) {41//get current charge int level = Intent.getintextra ("level", 0); 43//Total scale of the charge: int scales = Intent.getintextra ("scale", 10 0) Textview.settext ("Battery charge is" + ((level*100)/scale) + "%"); 46 47//When the battery is low, you can Do some actions, such as pop-up notifications, such as */if (level<15) {something50 do}*/51}52}53 54}55 56}
Immediately thereafter, the permission declaration is made in the manifest file:
<uses-permission android:name= "Android.permission.BATTERY_STATS"/>
The code for Mainactivity.java is interpreted as follows:
40 to 45 lines: fixed code to get current charge
48 to 50 rows: When the battery is low, you can do something, such as pop-up notifications, etc.
After running, the interface is as follows:
Android Component series----Broadcastreceiver broadcast receivers