Broadcast is an important feature of Android development, there are a variety of broadcasting in Android, such as: battery status changes, signal strength status, telephone answering and receiving SMS, and so on, now give you a brief introduction of the system to send, listen to the mechanism of these broadcasts.
The broadcasting mechanism in Android is basically as follows:
How does the broadcast work in the Android program? Now I'll give you a good analysis in the form of code:
First, send the broadcast
Intent is a bridge in the activity to send broadcasts, through which we can easily send the broadcast to the system, the specific implementation is as follows:
Final String intent_action = "Com.android.BroadcastReceiverDemo";//define the broadcast so that we receive this broadcast Intent Intent = new Intent (intent_ Action); Intent.putextra ("Name", "Millet"); Activityone.this.sendBroadcast (Intent);
You might wonder what intent_action is for, because there's a lot of broadcasts inside Android, and we can only receive this broadcast through Intent_action.
II. Reception of Broadcasts
When we receive a broadcast we need to define a subclass of Broadcastreceiver to receive our broadcasts, and to respond to the broadcast by overriding the Broadcastreceiver OnReceive () method.
public class Mybroadcastreceiver extends broadcastreceiver{@Overridepublic void onreceive (context context, Intent Intent) {//TODO auto-generated method stub String name = Intent.getstringextra ("name");//Gets the value passed by the broadcast issuer Toast.maketext ( Context, name, Toast.length_short). Show ();}
Third, configure the broadcast
<receiver android:name= "Cn.edu.hpu.android.activity_broadcast. Mybroadcastreceiver " android:enabled=" true " > <intent-filter > <action android: Name= "Com.android.BroadcastReceiverDemo"/> </intent-filter> </receiver>
Be sure to ensure that the android:name= "com.android.BroadcastReceiverDemo", the orange content and the settings we set intent_action when sending the broadcast. content is consistent.
Writing here basically has the Android broadcasting mechanism to tell everyone, if there is not the right place to look at the guidance.