Android--Simple broadcast receive and send (1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.