When a situation occurs on an Android system, all programs must be notified of processing, such as low power, and the broadcast intent object can be used to broadcast information.
The operating mechanism consists of two parts: The program that sends out the intent object, the program that listens to the broadcast information (broadcast Receiver), its province is a class, must inherit the Broadcastreceiver class, must register with the system, and specify the broadcast information to listen. When the broadcast message is sent out, all broadcast receiver programs that listen to the broadcast message are started and the OnReceive () method is run.
The broadcast receiver program is only valid if the Android system is running its onreceive () method, and may be removed once it is run, until the next listening broadcast message appears to run again. So asynchronous work like the more time-consuming thread is not suitable for running in onreceive ().
1. Establish the intent object and specify the message to broadcast.
Intent it = new Intent ("Tw.android.MY_BROADCAST"); It.putextra ("Sender", "broadcast receive~");//with data, data placed in intent object //Using bundle object to deposit intent Object Bundle bundle = new Bundle (); Bundle.putstring ("Sender", "broadcast receive~"); It.putextras (bundle);
2. Call the Sendbroadcast () method to broadcast the intent object.
Sendbroadcast (IT);
3. To create a new class that inherits the broadcast receiver class, the OnReceive () method needs to be implemented.
public class Mybroadcast extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) {//TOD O auto-generated Method Stub //Implements the methods to be run when a listening broadcast message appears, where the intent object is a onreceive () argument without calling Getintent () to obtain
4, in the main program to the Android system to register the broadcast Receiver established in the previous step, and to listen to the broadcast message.
Register in the Androidmanifest.xml in the program project:
<application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@ String/app_name " 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> <receiver android:name= ". Mybroadcast" android:label= "@string/app_name" > <intent-filter > <action android:name= "Tw.android.MY_BROADCAST"/> </intent-filter> </receiver> </application>
Registering and canceling registrations in the program:
Intentfilter itfilter = new Intentfilter ("Tw.android.MY_BROADCAST"); Mybroadcast mybroadcast = new Mybroadcast (); Registerreceiver (mybroadcast,itfilter); ... Unregisterreceiver (mybroadcast);//Cancel Registration
Can be canceled only if registered in the program.
Broadcast Intent & Broadcast Receiver