Explanation of BroadcastReceiver in Android Development

Source: Internet
Author: User

Explanation of BroadcastReceiver in Android Development

BroadcastReceiver, as its name implies, is the meaning of "broadcast receiver". It is one of the four basic components of Android. This component is essentially a global listener used to listen to global broadcast messages of the system. It can receive broadcasts from systems and applications.

Because BroadcastReceiver is a global listener, it can easily implement communication between different components of the system. For example, you can use BroadcastReceiver to implement communication between an Activity and a Service started using the startService () method.

BroadcastReceiver introduction:

BroadcastReceiver is used to receive Broadcast intents sent by programs (including system programs and general applications) through the sendBroadcast () method.

Procedure for the program to start BroadcastReceiver (send broadcast ):

1) Create an Intent that needs to start BroadcastReceiver.

2) Call the ContextsendBroadcast() Or sendOrderedBroadcast() Method to start the specified BroadcastReceiver. WheresendBroadcastThe sendOrderedBroadcast and sendOrderedBroadcast send normal broadcasts.

Components that match the Broadcast Intent may be started when the application sends out a Broadcast Intent.

To create a BroadcastReceiver, follow these steps:

Step 1: Create a subclass of BroadcastReceiver:

Because BroadcastReceiver is essentially a listener, the method for creating BroadcastReceiver is also very simple. You only need to create a subclass of BroadcastReceiver and then override the onReceive (Context context, Intentintent) method.

The 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 2: Register BroadcastReceiver

Once BroadcastReceiver is implemented, you should specify the Intent that the BroadcastReceiver can match to register BroadcastReceiver. You can register BroadcastReceiver in either of the following ways:

First, static registration: This method is used to configure AndroidManifest. in the xml configuration file, the broadcast registered in this way is resident broadcast. That is to say, if the application is closed and the corresponding event is triggered, the program will still be automatically called and run by the system. For example:

 
     
                  
       
  
  

The second is dynamic registration.: The code is registered in the. Java file. The broadcast registered in this way is non-resident, that is, it will follow the lifecycle of the Activity. Therefore, before the Activity ends, we need to call the unregisterReceiver (Referer) method to remove it. For example:

// Dynamically register MyBroadcastReceiverMyBroadcastReceiver using code = new MyBroadcastReceiver (); IntentFilter filter = new IntentFilter (); filter. addAction ("android. intent. action. myBroadcastReceiver "); // register receiverregisterReceiver (receiver er, filter );

Note:If BroadcastReceiver is registered in the Activity, you must cancel the registration when the Activity is destroyed. Otherwise, an exception occurs. The method is as follows:

@ Override protected void onDestroy () {// TODO Auto-generated method stub super. onDestroy (); // cancel registering BroadcastReceiver unregisterReceiver (reporter ER) when the Activity is destroyed );}

BroadcastReceiver lifecycle:

The life cycle of BroadcastReceiver, from the time when the object calls it, to the time when the onReceiver method is executed. In addition, after each broadcast is received, the BroadcastReceiver object is re-created and destroyed after the onReceiver method is executed. If the onReceiver method of BroadcastReceiver cannot be executed within 10 seconds, android has an ANR exception. Therefore, do not perform time-consuming operations in the BroadcastReceiver onReceiver method.

To perform time-consuming operations in BroadcastReceiver, you can use Intent to start the Service. But cannot bind a Service.

In particular, you may not be able to display a dialog box from a BroadcastReceiver or bind it to a service. For the former, the icationicationmanager API should be used. For the latter, you can use Context. startService () to start a Service.

Broadcast type:

Broadcast has two types: normal Broadcast and ordered Broadcast.

Normal broadcasts(Normal broadcast): Normal broadcasts is completely asynchronous and can be received by all receivers at the same time. Message transmission efficiency is relatively high. The disadvantage is that the receiver cannot transmit the processing information of the received message to the next receiver or stop the message propagation.

Ordered broadcasts(Ordered broadcast): the receiver of Ordered broadcasts receives messages according to a certain priority. For example, if the priority of A, B, and C is reduced in turn, the message is first transmitted to A, then transmitted to B, and finally to C. Priority levels are stated in Medium, the value is [-]. The greater the value, the higher the priority. You can also set the priority by using filter. setPriority (10. In addition, the receiver of Ordered broadcasts can cancel Broadcast propagation by means of abortBroadcast (), or save the processing result to Broadcast through setResultData and setResultExtras, and pass it to the next receiver. Then, the next receiver receives the data stored by the high-priority receiver through getResultData () and getResultExtras (true.

Application instance:

Send and receive normal 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:
*
This instance has two broadcast receivers with different priority levels *
Learn by sending normal broadcasts and ordered broadcasts *
Principle of BroadcastReceiver *
@ Author jph *
@ Date: 2014.08.05 **/public class MainActivity extends Activity {MyBroadcastReceiver extends er; 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 ER = new MyBroadcastReceiver (); OnClickListener listener = New OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. btnSend: Intent intent = new Intent (); intent. setAction ("android. intent. action. myBroadcastReceiver "); intent. putExtra ("msg", "I'm sending a broadcast! This is just a normal broadcast. "+" you cannot stop broadcasting in the abortBroadcast () mode, "+" cannot store data in Broadcast either 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 ordered broadcast, "+" you can stop broadcasting in abortBroadcast () mode, "+" You can also store data in Broadcast "); sendOrderedBroadcast (intent2, null); break; default: break ;}}; btnSend. setOnClickListener (listener); btnSend2.setOnClickListener (listener );}}
MyBroadcastReceiver. java: receives Broadcast

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:
*
@ Author jph *
@ Date: 2014.08.05 **/public class MyBroadcastReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// TODO Auto-generated method stubString msg = intent. getExtras (). get ("msg "). toString (); setResultData ("MyBroadcastReceiver receives broadcast"); Toast. makeText (context, "Time:" + new SimpleDateFormat ("yyyy-MM-dd hh. mm. ss "). format (new Date () + "\ nMyBroadcastReceiver receives the Action name:" + intent. getAction (). toString () + "broadcast \ nComponent:" + intent. getComponent () + "\ nmsg:" + msg, Toast. LENGTH_LONG ). show ();}}
SecondBroadcastReceiver. java receives Broadcast

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:
*
@ Author jph *
@ Date: 2014.08.05 **/public class SecondBroadcastReceiver 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 + "\ n the reult from the previous receiver:" + result, Toast. LENGTH_LONG ). show ();}}
Configuration File AndroidManifest. xml:

 
     
                          
                                  
               
          
  
      
                   
        
   
  
  
      
                   
        
   
      
 





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.