Original link: http://www.cnblogs.com/zyw-205520/archive/2013/01/25/2876882.html
In activity, register a demo of the broadcast.
A total of 3 steps
First step: Define a Broadcastreceiver broadcast receive class:
View Plain
Private Broadcastreceiver Mbroadcastreceiver = new Broadcastreceiver () {
@Override
public void OnReceive (context context, Intent Intent) {
String action = Intent.getaction ();
if (action.equals (Action_name)) {
Toast.makeText ( Test.this, "handling the broadcast corresponding to the action name",
}
};
Step Two: Register the broadcast:
View Plain
public void Registerboradcastreceiver () {
Intentfilter myintentfilter = new Intentfilter ();
Myintentfilter.addaction (Action_name);
Register a broadcast
Registerreceiver (Mbroadcastreceiver, Myintentfilter);
}
Step three: Trigger the response
View Plain
Mbtnmsgevent = new Button (this);
Mbtnmsgevent.settext ("Send broadcast");
Mbtnmsgevent.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
Intent mintent = new Intent (action_name);
Mintent.putextra ("Yaner", "send broadcast, equivalent to transmit data here");
Send broadcast
Sendbroadcast (mintent);
}
});
PackageCom.zyw.Broadcast; Importandroid.app.Activity;ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;Importandroid.widget.LinearLayout;ImportAndroid.widget.Toast; Public classTestextendsactivity{Private FinalString action_name = "Send Broadcast"; PrivateButton mbtnmsgevent =NULL; protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Register a broadcastRegisterboradcastreceiver (); LinearLayout Mlinearlayout=NewLinearLayout ( This); Mbtnmsgevent=NewButton ( This); Mbtnmsgevent.settext ("Send Broadcast"); Mlinearlayout.addview (mbtnmsgevent); Setcontentview (mlinearlayout); Mbtnmsgevent.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Intent mintent=NewIntent (action_name); Mintent.putextra ("Yaner", "send broadcast, equivalent to transmit data here"); //Send broadcastSendbroadcast (mintent); } }); } PrivateBroadcastreceiver Mbroadcastreceiver =NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {String action=intent.getaction (); if(Action.equals (action_name)) {Toast.maketext (Test. This, "processing the broadcast corresponding to the action name", 200); } } }; Public voidRegisterboradcastreceiver () {intentfilter myintentfilter=NewIntentfilter (); Myintentfilter.addaction (Action_name); //Register a broadcastregisterreceiver (Mbroadcastreceiver, Myintentfilter); } }
Use of Android Broadcast