Android Development Learning Path--broadcast receiver first experience

Source: Internet
Author: User

Once you have learned the activity component, you will learn another component broadcast receiver component. Learn about the custom broadcast Receiver here. Send the broadcast yourself by pressing the key and then receive the broadcast yourself. Create a new mybroadcastreceiver with the following code:

Package Com.example.jared.broadcasttest;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import android.widget.toast;/** * Created by Jared on 16/2/12. */public class Mybroadcastreceiver extends Broadcastreceiver {    @Override public    void OnReceive (Context context , Intent Intent) {        Toast.maketext (context, "Received from Mybroadcastreceiver",                Toast.length_long). Show ();    }}

then add the receiver tag in the androidmanifest:

<receiver android:name= ". Mybroadcastreceiver ">            <intent-filter>                <action android:name=" com.example.broadcasttest.MY_ Broadcast "/>            </intent-filter>        </receiver>
This defines the broadcast of the message as Com.example.broadcasttest.MY_BROADCAST.

Modify Activity_main.xml as follows to add a button control:

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout    xmlns:android= "http://schemas.android.com/apk /res/android "    xmlns:tools=" Http://schemas.android.com/tools "    android:layout_width=" Match_parent    " android:layout_height= "Match_parent"    android:paddingleft= "@dimen/activity_horizontal_margin"    android: paddingright= "@dimen/activity_horizontal_margin"    android:paddingtop= "@dimen/activity_vertical_margin"    android:paddingbottom= "@dimen/activity_vertical_margin"    tools:context= " Com.example.jared.broadcasttest.MainActivity ">    <button        android:id=" @+id/send "        android: Layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "Send mybroadcast"        android:textallcaps= "false"/></relativelayout>

then modify the mainactivity and add the following:

        Send = (Button) Findviewbyid (r.id.send);        Send.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (view view) {                Intent Intent = new Intent ("Com.example.broadcasttest.MY_BROADCAST");                Sendbroadcast (intent);            }        });
The intent is used here, and when the button is pressed, a broadcast called Com.example.broadcasttest.MY_BROADCAST is Sendbroadcast.

Then run to see the effect:


In fact, the broadcast is a cross-process, different processes between the different apps can be passed to each other. Here we have installed the Broadcasttest app, and then create a new app to receive this message. New BroadcastTest2.

Then add otherbroadcastreceiver with the following code:

Package Com.example.jared.broadcasttest2;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import android.widget.toast;/** * Created by Jared on 16/2/12. */public class Otherbroadcastreceiver extends Broadcastreceiver {    @Override public    void OnReceive (Context Context, Intent Intent) {        Toast.maketext (context, "Receive by otherbroadcastreceiver!",                Toast.length_long). Show ();    }}
Add the Androidmanifest code as follows:

  <receiver android:name= ". Otherbroadcastreceiver ">            <intent-filter>                <action android:name=" Com.example.broadcasttest.MY _broadcast "/>            </intent-filter>        </receiver>

then run the code, press the home button back to the background, then run the above installed app, and then run, the effect is as follows:



You can see that two broadcasts have been received. and send it one at a time. Then we learn the priority of the broadcast reception, here we only need to modify two places, one is the sending function, the Sendbroadcast function is replaced with sendorderedbroadcast, and then add Android in Androidmanifest: The priority attribute. The broadcast can then be truncated by the Abortbroadcast method. Let's take a look at the example.

Modify the code for the Broadcasttest project as follows:

Send = (Button) Findviewbyid (r.id.send);        Send.setonclicklistener (New View.onclicklistener () {            @Override public            void OnClick (view view) {                Intent Intent = new Intent ("Com.example.broadcasttest.MY_BROADCAST");                Sendorderedbroadcast (intent, NULL);            }        });

after modifying the received broadcast, truncate the broadcast with the following code:

public class Mybroadcastreceiver extends Broadcastreceiver {    @Override public    void OnReceive (context context, Intent Intent) {        Toast.maketext (context, "Received from Mybroadcastreceiver",                Toast.length_long). Show ();        Abortbroadcast ();    }}

To Modify Androidmanifest Add priority:

        <receiver android:name= ". Mybroadcastreceiver ">            <intent-filter android:priority=" >                <action android:name= " Com.example.broadcasttest.MY_BROADCAST "/>            </intent-filter>        </receiver>

then run the view effect, only the current app receives the broadcast, and the other app doesn't receive any broadcasts. Has also met our expectations.

After studying the local broadcast, the so-called local, is only the current app can receive the broadcast, the other apps are not receiving this broadcast. Create a new Localbroadcast project and write the following code:

Package Com.example.jared.localbroadcast;import Android.content.broadcastreceiver;import Android.content.Context; Import Android.content.intent;import Android.content.intentfilter;import Android.support.v4.content.localbroadcastmanager;import Android.support.v7.app.appcompatactivity;import Android.os.bundle;import Android.view.view;import Android.widget.button;import Android.widget.Toast;public class    Mainactivity extends Appcompatactivity {private Intentfilter intentfilter;    Private Localreceiver Localreceiver;    Private Localbroadcastmanager Localbroadcastmanager;    Private Button send;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Intentfilter = new Intentfilter ();        Intentfilter.addaction ("Com.example.localbroadcast.LOCAL_BROADCAST");        Localreceiver = new Localreceiver ();     Localbroadcastmanager = Localbroadcastmanager.getinstance (this);   Localbroadcastmanager.registerreceiver (Localreceiver, Intentfilter);        Send = (Button) Findviewbyid (r.id.send);                Send.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {                Intent Intent = new Intent ("Com.example.localbroadcast.LOCAL_BROADCAST");            Localbroadcastmanager.sendbroadcast (Intent);    }        });        } @Override protected void OnDestroy () {Super.ondestroy ();    Localbroadcastmanager.unregisterreceiver (Localreceiver);  } class Localreceiver extends Broadcastreceiver {@Override public void onreceive (context context, Intent        Intent) {Toast.maketext (context, "Localreciver received", Toast.length_long). Show (); }    }}

a localbroadcastmanager is registered here, with the name Com.example.localbroadcast.LOCAL_BROADCAST. Dynamic registration via Intentfilter. The inner class Localreceiver inherits Broadcastreceiver and overrides the OnReceive method, which receives a broadcast reminder under the toast message feedback.

The results are as follows:


About broadcast receiver on the basic learning here, first learn the basics, and then further study.

Tomorrow to work, fortunately, the new year also learned some knowledge, we have to speed up the first line of code, and then continue to study hard, as soon as possible to do the work of Android development, early to do what they want to do.


Attached: Refer to the first line of code

Android Development Learning Path--broadcast receiver first experience

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.