Broadcastreceiver of Android Development

Source: Internet
Author: User

Broadcastreceiver, as the name implies, is "broadcast receiver", which is one of the four basic components of Android, which is essentially a global listener to listen to the system's global broadcast messages. It can receive broadcasts from systems and applications.

Because Broadcastreceiver is a global listener, it makes it very easy to communicate between different components of the system. For example, the activity is communicated with the service initiated by the StartService () method, which can be accomplished by means of broadcastreceiver.

Broadcastreceiver Introduction:

The broadcastreceiver is used to receive broadcast intents from programs (including system programs and general applications) that are emitted through the sendbroadcast () method.

procedure to start broadcastreceiver (issue a broadcast):

1) Create a intent that needs to start broadcastreceiver.

2) Call the context's sendBroadcast () or endOrderedBroadcast s() method to start the specified broadcastreceiver. It sendBroadcast sends a regular broadcast, andSendorderedbroadcast sends an orderly broadcast.

when the app emits a Broadcast Intent after that, the matching Intent components may be started.

steps to create Broadcastreceiver:

First step: Create Broadcastreceiver sub-class:

Since Broadcastreceiver is essentially a listener, the method of creating broadcastreceiver is very simple, just create a broadcastreceiver subclass and rewrite onreceive( context context, IntentIntent) method can be.

The specific code is as follows:

public class Mybroadcastreceiver extends Broadcastreceiver {         @Override public         void OnReceive (context context, Intent Intent) {                   //TODO auto-generated method stub                   String Msg=intent.getextras (). Get ("MSG"). toString ();                   Toast.maketext (Context, "intent.getaction ()" +intent.getaction (). toString (),                                     Toast.length_long). Show ();                   System.out.println ("msg:" +msg);}         }

Step Two: Register broadcastreceiver

Once the broadcastreceiver is implemented, it should be specified that the Broadcastreceiver can match the intent that is registered broadcastreceiver. There are two ways to register Broadcastreceiver:

The first is static registration : This method is registered in the configuration androidmanifest.xml configuration file, the broadcast registered in this way is a resident broadcast, that is, if the application is closed, a corresponding event is triggered, The program will still be run automatically by the system . For example:

<!--register Broadcastreceiver in the config file to match intent--><receiver android:name= " Com.example.test.MyBroadcastReceiver ">    <intent-filter>        <action android:name=" Android.intent.action.MyBroadcastReceiver "></action>        <category android:name=" Android.intent.category.DEFAULT "></category>    

The second type is dynamic registration: This approach is done through code. The Java file to register.the broadcast registered in this way is a very resident broadcast, that is, it will followActivitylife cycle, so inActivityBefore we end we need to callunregisterreceiver (receiver)method to remove it。 For example:

Dynamic registration via Code Mybroadcastreceivermybroadcastreceiver receiver=new mybroadcastreceiver (); Intentfilter filter=new Intentfilter (); Filter.addaction ("Android.intent.action.MyBroadcastReceiver");//Registered Receiverregisterreceiver ( receiver, filter);

Note:If we register the activity with the broadcastreceiver, the activity will be destroyed when the active revocation of the registration or the exception occurs.methods are as follows:

         @Override         protected void OnDestroy () {                   //TODO auto-generated method Stub                   Super.ondestroy ();                   Unregister broadcastreceiver                   unregisterreceiver (receiver) when activity is destroyed;         }

the life cycle of Broadcastreceiver:

The life cycle of the broadcastreceiver, starting with the object invocation and ending with the completion of the Onreceiver method execution. In addition, after each broadcast is received, the Broadcastreceiver object is recreated and destroyed after execution in the Onreceiver method, if the Broadcastreceiver Onreceiver method cannot be completed within 10 seconds, There is a ANR exception on Android. so don't at Broadcastreceiver of the Onreceiver method to perform time-consuming operations.

If you need to perform time-consuming operations in Broadcastreceiver, you can do so by intent starting the service. However, the service cannot be bound.

in particular, you may not be able to get from a Broadcastreceiver A dialog box is displayed or bound to a service. For the former, you should use the notificationmanager API. For the latter, you can use context.startservice () to start a Service.

type of broadcast:

There are two types of broadcast: Normal broadcast and ordered broadcast.

normal broadcasts (normal broadcast): The Normal broadcasts is completely asynchronous and can be received by all recipients at the same time. Message delivery efficiency is high. However, the disadvantage is that the recipient cannot tell the receiving message that the processing information is passed to the next recipient and cannot stop the message from being propagated.

Ordered broadcasts(ordered broadcast): The recipient ofOrdered broadcasts receives the message according to a certain priority. For example, if the priority of the a,b,c is reduced in turn, then the message is passed to A, passed to B, and finally passed to C. Priority declaration in <intent-filter> , the greater the value of [ -1000,1000], the higher the priority level. The priority is also available through the filter. setpriority (10) Mode setting. In addition, recipients of Ordered broadcasts can cancel the broadcast by Abortbroadcast(), or through setresultdata and The Setresultextras method stores the processed results in broadcast and passes them to the next recipient. The next recipient then receives the data deposited by the high-priority recipient via Getresultdata() and Getresultextras(true).

Application Examples:

Send and receive regular and ordered broadcasts:

Run:


Instance code:

Mainactivity.java: Send broadcast:

Package Com.jph.broadcastreceiverdemo;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.app.activity;import android.content.intent;/** * describe:</br> * <br/> This instance has two different priority broadcast receivers * <br/> learn by sending regular broadcasts and ordered broadcasts * Principle of <br/>broadcastreceiver * <br/> @author JPH * <br/> @Date: 2014.08.05 * */public class Mainactivity Extends Activity {mybroadcastreceiver receiver; Button btnsend,btnsend2; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); btnsend= (Button) Findviewbyid (r.id.btnsend); btnSend2 = (Button) Findviewbyid (r.id.btnsend2); receiver=new mybroadcastreceiver (); Onclicklistener listener=new Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case r.id.b Tnsend:intent intent=new Intent (); Intent.setaction ("Android.intent.action.MyBroadcastReceiver"); Intent.putextra ("msg", "I'm sending a broadcast!") This is just an ordinary broadcast, "+" You cannot stop the broadcast by Abortbroadcast (), "+" cannot deposit data into the broadcast because it is asynchronous "); Sendbroadcast (intent); break;case R.id.btnsend2:intent intent2=new Intent (); Intent2.setaction ("Android.intent.action.MyBroadcastReceiver"); Intent2.putextra ("msg", "I am sending an orderly broadcast," + "You can stop the broadcast by Abortbroadcast ()," + "can also deposit data into the broadcast"); Sendorderedbroadcast (Intent2, null); break;default:break;}}; Btnsend.setonclicklistener (listener); Btnsend2.setonclicklistener (listener);}}
Mybroadcastreceiver.java: Receiving broadcasts

Package Com.jph.broadcastreceiverdemo;import Java.text.simpledateformat;import Java.util.date;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import android.widget.toast;/** * describe:</br> * <br/> @author JPH * <br/> @Date: 2014.08.05 * */public class M Ybroadcastreceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) {//TODO Aut O-generated method Stubstring Msg=intent.getextras (). Get ("MSG"). toString (); Setresultdata (" Mybroadcastreceiver received the broadcast "); Toast.maketext (Context, "Time:" +new simpledateformat ("Yyyy-mm-dd hh.mm.ss"). Format (new Date ()) + "\ Nmybroadcastreceiver received the action name: "+intent.getaction (). toString () +" broadcast \ncomponent: "+intent.getcomponent () +" \nmsg: "+msg,toast.length_long"). Show ();}}
Secondbroadcastreceiver.java Receiving broadcasts

Package Com.jph.broadcastreceiverdemo;import Java.text.simpledateformat;import Java.util.date;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import android.widget.toast;/** * describe:</br> * <br/> @author JPH * <br/> @Date: 2014.08.05 * */public class S Econdbroadcastreceiver extends Broadcastreceiver {@Overridepublic void OnReceive (context context, Intent Intent) {// TODO auto-generated Method Stubstring Msg=intent.getextras (). Get ("MSG"). toString (); String Result=getresultdata (); Toast.maketext (Context, "Time:" +new simpledateformat ("Yyyy-mm-dd hh.mm.ss"). Format (new Date ()) + "\ Nsecondbroadcastreceiver received the action name: "+intent.getaction (). toString () +" broadcast \ncomponent: "+intent.getcomponent () +" \ Nmsg: "+msg+" \ nthe last recipient of the Reult: "+result,toast.length_long". Show ();}}
configuration file Androidmanifest.xml:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.jph.broadcastreceiverdemo "android:versioncode=" 1 "android:versionname=" 1.0 "> <us ES-SDK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allow" Backup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@s Tyle/apptheme "> <activity android:name=" com.jph.broadcastreceiverdemo.MainActivity "an Droid:label= "@string/app_name" > <intent-filter> <action android:name= "Android.inten T.action.main "/> <category android:name=" Android.intent.category.LAUNCHER "/> </int ent-filter> </activity><!--Register mybroadcastreceiver to match intent--><receiver Android:name= "Co in the configuration file M.jph.broadcastreceiverdemo.mybroadcastrEceiver "> <intent-filter android:priority=" > <action android:name= "android.intent.action.MyBroad Castreceiver "></action> <category android:name=" Android.intent.category.DEFAULT "></category > </intent-filter></receiver><!--Register Secondbroadcastreceiver in the configuration file to match intent--><receiver Android:name= "Com.jph.broadcastreceiverdemo.SecondBroadcastReceiver" > <intent-filter android:priority= "100 "> <action android:name=" android.intent.action.MyBroadcastReceiver "></action> <category an Droid:name= "Android.intent.category.DEFAULT" ></category> </intent-filter></receiver> </ Application></manifest>





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.