1.
2. Implementing the Code
Layout.xml
<button android:id= "@+id/testbtn" android:layout_width= "match_parent" android:layout_height= " Wrap_content " android:text=" @string/hello_world "/>
Mainactivity.java
public static final String my_action = "Iflab.test.MY_ACTION"; Custom Actionprivate Button testbtn; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); testbtn = (Button) Findviewbyid (R.ID.TESTBTN); Testbtn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubintent Intent = new Intent (); intent.setaction (my_action); Intent.putextra ("message", "Messages from broadcast!") "); Set the broadcast message sendbroadcast (intent);}});}
Testbroadcastreceiver.java
public class Testbroadcastreceiver extends Broadcastreceiver {//Context object Intent received intent object @overridepublic void onrecei ve (context context, Intent Intent) {//TODO auto-generated method Stubstring Str;str = "received broadcast message:" + intent.getstringextr A ("message"); Receive Message Toast.maketext (context, str, toast.length_short). Show ();}}
Information to fill in the configuration file
<receiver android:name= "Testbroadcastreceiver" > <intent-filter> <action android:name= " Iflab.test.MY_ACTION "/> </intent-filter> </receiver>
3. Description
<action android:name= "Iflab.test.MY_ACTION"/> is the constant you define in mainactivity
<receiver android:name= "Testbroadcastreceiver" > name is the class that you start when you want to receive the broadcast Testbroadcastreceiver
Android--Simple broadcast receive and send (1)