The previous section learned how to create a broadcast, and also try to receive a broadcast that the system calls. This lesson learns how to customize broadcasts. Custom broadcasts essentially create a send broadcaster and create a recipient to accept the broadcast.
Then let's get to the action.
First create an app that sends the broadcast:
public class Mainactivity extends Activity { @Override protected void onCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); } public void Sendbroadcast (View v) { //broadcast send is also Intent sent, the data is also used Intent value Intent Intent = new Intent (); Set the action for this broadcast to be used by the recipient to introduce intent.setaction ("Com.demo.broadcastReceiver"); Set the broadcast data Intent.putextra ("broadcast", "Hello, you receive 3wRMB salary this month!!!" "); Send broadcast sendbroadcast (intent); }}
When you click the Send radio button, a custom broadcast is sent
Then create another app to receive the broadcast:
public class Mybroadcastreceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) {//TODO auto-generated method stub//The data bundle of the broadcast is the DataSource = Intent.getextras (); String broadstring = data.getstring ("broadcast");//Display Toast.maketext (context, broadstring, 0). Show ();}}
Remember that this broadcast recipient must be configured in the manifest file:
<receiver android:name= "Com.demo.broadcastreceiveractivity.MyBroadcastReceiver" > <intent-filter > <action android:name= "Com.demo.broadcastReceiver"/> </intent-filter> </receiver >
The broadcast recipient's action must be the same as the action set at the time of customization, or the broadcast will not be introduced
The demo works as follows:
As you can see, you did receive a custom broadcast.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Four components Learning Broadcastreceiver II