Android--The use of Broadcastreceiver

Source: Internet
Author: User

Broadcastreceiver is the meaning of "broadcast receiver", as its name implies, it is used to receive broadcasts from systems and applications.
In the Android system, the broadcast is reflected in all aspects, such as when the system will generate a broadcast after the boot, receive this broadcast can realize the function of starting the service, when the network state changes, the system will generate a broadcast, receive this broadcast can be timely to make prompt and save data and other operations When the battery level changes, the system will generate a broadcast, receiving this broadcast will be able to notify users of low battery time to save progress, and so on.
The broadcast mechanism in Android is very well designed, and many things need to be done by the developers themselves, and now just wait for the broadcast to tell themselves, greatly reducing the development effort and development cycle. And as an application developer, it takes a few exercises to master the Android system to provide a development tool, that is broadcastreceiver.

Broadcastreceiver Simple to use

The first step,
Let's take a look at the effect we're going to accomplish.
New project, create an activity and add a button to send the broadcast to the broadcast class we created.

Step Two,
The Myreceiver code we created is as follows,

package com.example.learnbroadcastreceiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;publicclass MyReceiver extends BroadcastReceiver {    @Override    publicvoidonReceive(Context context, Intent intent) {        System.out.println("接收到了消息");    }}

The third step,
Add an event to the button on the Activity page, and the button sends a message to Myreceiver,

    @Override    publicvoidonClick(View v) {        switch(v.getId()){        case R.id.button1:            sendBroadcast(new Intent(this, MyReceiver.class));            break;        }    }

Fourth Step,
We need to register for Myreceiver, in \androidmanifest.xml
If you go to the application label,

        <receiver             android:name=".MyReceiver"            android:enabled="true"            android:exported="true">        </receiver>

Fifth Step,
Running the code, receiver successfully received the message.

Registration and logoff of Broadcastreceiver

At this point, if we remove the Androidmanifest.xml,broadcastreceiver configuration, the communication will not be so. (Step fourth above)

More information: http://blog.csdn.net/liuhe688/article/details/6955668
Let's end the use of dynamic binding and deallocation

The first step,
On the page we add 2 more Buttons "bind", "Unbind"

Step Two,
To add a time method to the button, the code is as follows

 PackageCom.example.learnbroadcastreceiver;Importandroid.app.Activity;ImportAndroid.content.Intent;ImportAndroid.content.IntentFilter;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener; Public  class mainactivity extends Activity implements Onclicklistener  {    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Findviewbyid (R.id.button1). Setonclicklistener ( This); Findviewbyid (R.id.button2). Setonclicklistener ( This); Findviewbyid (R.id.button3). Setonclicklistener ( This); }@Override     Public Boolean Oncreateoptionsmenu(Menu menu) {//inflate the menu; This adds items to the action bar if it is present.Getmenuinflater (). Inflate (R.menu.main, menu);return true; }@Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.button1://Sendbroadcast (new Intent (this, myreceiver.class));Intent Intent =NewIntent ("Com.example.learnbroadcastreceiver.intent.action.MyReceiver"); Sendbroadcast (Intent); Break; CaseR.id.button2:if(Myreceiver = =NULL) {Myreceiver =NewMyreceiver (); Registerreceiver (Myreceiver,NewIntentfilter ("Com.example.learnbroadcastreceiver.intent.action.MyReceiver")); } Break; CaseR.id.button3:if(Myreceiver! =NULL) {unregisterreceiver (myreceiver); Myreceiver =NULL; } Break; }    }PrivateMyreceiver Myreceiver =NULL;}

The core code is 32-49 lines, which are send, bind, unbind, and use 3 operations.

At this point, a bound and unbound operation is complete.

Android--The use of Broadcastreceiver

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.