Transfer data between Android broadcast receivers and activity

Source: Internet
Author: User

  Activity transmits data to the broadcast receiver simply by put the data into the intent before sending the broadcast.

How does a broadcast receiver transmit data to the activity? The interface is used here, by defining an interface in the broadcast receiver, and then the activity that receives the broadcast receiver data implements the interface. First look at the chestnut below, the activity sends a broadcast, and then the broadcast receiver returns a string.

Activity layout File

1 <?XML version= "1.0" encoding= "Utf-8"?>2 <LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Xmlns:tools= "Http://schemas.android.com/tools"4 Android:layout_width= "Match_parent"5 Android:layout_height= "Match_parent"6 android:orientation= "vertical"7 Tools:context= "Com.nangch.broadcastreceivertest.MainActivity">8 9     <TextViewTen         Android:id= "@+id/tv" One Android:layout_width= "Wrap_content" A Android:layout_height= "Wrap_content" - Android:text= "Hello" /> -  the     <Button -         Android:id= "@+id/btn" - Android:layout_width= "Match_parent" - Android:layout_height= "Wrap_content" + Android:text= "Send Broadcast"/> - </LinearLayout>

Activity Code

1 Importandroid.content.Intent;2 ImportAndroid.content.IntentFilter;3 ImportAndroid.os.Bundle;4 Importandroid.support.v7.app.AppCompatActivity;5 ImportAndroid.view.View;6 ImportAndroid.widget.Button;7 ImportAndroid.widget.TextView;8 9  Public classMainactivityextendsAppcompatactivityImplementsmyreceiver.message{Ten  One TextView TV; A myreceiver Myreceiver; -  - @Override the     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); -  +         //registering a broadcast receiver -Myreceiver =Newmyreceiver (); +Intentfilter Intentfilter =NewIntentfilter (); AIntentfilter.addaction ("Com.nangch.broadcasereceiver.MYRECEIVER"); at registerreceiver (Myreceiver, intentfilter); -  -         //because the message needs to be injected here, the broadcast sink cannot be statically registered in the Androidmanifest file -Myreceiver.setmessage ( This); -  -TV =(TextView) Findviewbyid (r.id.tv); inButton BTN =(Button) Findviewbyid (R.ID.BTN); -Btn.setonclicklistener (NewView.onclicklistener () { to @Override +              Public voidOnClick (View v) { -Intent Intent =NewIntent ("Com.nangch.broadcasereceiver.MYRECEIVER"); theIntent.putextra ("Hello", Tv.gettext ());//passing data to a broadcast receiver *Sendbroadcast (Intent);//Send broadcast $             }Panax Notoginseng         }); -     } the  + @Override A      Public voidgetmsg (String str) { the         //The data in the Myreceiver can be processed here by implementing the Myreceiver.message interface + tv.append (str); -     } $  $ @Override -     protected voidOnDestroy () { -         Super. OnDestroy (); theUnregisterreceiver (Myreceiver);//unregister a broadcast sink -     }Wuyi}

Broadcast receiver Code

1 ImportAndroid.content.BroadcastReceiver;2 ImportAndroid.content.Context;3 Importandroid.content.Intent;4 ImportAndroid.widget.Toast;5 6  Public classMyreceiverextendsBroadcastreceiver {7     Privatemessage message;8 9 @OverrideTen      Public voidOnReceive (Context context, Intent Intent) { One         //receive the data sent by Mainactivity AToast.maketext (Context, Intent.getstringextra ("Hello"), Toast.length_short). Show (); -  -         //methods for invoking the message interface theMessage.getmsg ("World"); -     } -  -     InterfaceMessage { +          Public voidgetmsg (String str); -     } +  A      Public voidsetmessage (Message message) { at          This. Message =message; -     } -}

As follows:

After clicking the Send Broadcast button:

Defines a message interface in Myreceiver and declares a member variable message of type message. Then let mainactivity implement this interface, and call the Setmessage method to inject mainactivity, so that the mainactivity instance becomes the Myreceiver member variable message, This will handle the data in the Myreceiver. This idea is similar to the idea of setting a button listener when we learn Android, and it's good to think about it.

Demo instance Source download

Transfer data between Android broadcast receivers and activity

Related Article

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.