Four major Android components-Explanation of Broadcast Receiver

Source: Internet
Author: User

This article mainly describes:

I. Overview of BroadcastReceiver:

Ii. BroadcastReceiver event Classification

3. BroadcastReceiver event Programming process

Iv. Two types of BroadcastReceiver

5. Normal broadcast and ordered Broadcast

6. How does the Service interact with BroadcastReceiver?

7. automatically run the service at startup

8. BroadcastReceiver Lifecycle


I. Overview of BroadcastReceiver:

1. A broadcast receiver is a component that focuses on receiving and processing broadcast notifications. Many broadcasts originate from system code, such as notifying time zone changes, low battery, taking a picture, or changing language options. Applications can also be broadcast-for example, to notify other applications that some data has been downloaded and is available.
2. An application can have any number of broadcast receivers to respond to all notifications that interest it. All receivers inherit from the BroadcastReceiver base class.
2. The broadcast receiver has no user interface. However, they can start an activity to respond to the information they receive, or use icationicationmanager to notify users. Notifications can be used in many ways to attract users' attention-flashing back lights, vibrations, and playing sounds. In general, a persistent icon is placed on the status bar. You can open it and get the message.


Ii. BroadcastReceiver event Classification

1. System broadcast events, such as: ACTION_BOOT_COMPLETED (triggered after the system starts), ACTION_TIME_CHANGED (triggered when the system time changes), ACTION_BATTERY_LOW (triggered when the power is low), and so on.

2. Custom broadcast events.


3. BroadcastReceiver event Programming process

1. Register broadcast events: There are two registration methods,

Static registration is defined in the AndroidManifest. xml file. The registered broadcast receiver must inherit the BroadcastReceiver class;

Register tags in AndroidManifest. xml and set filters in tags.

 
  
// Inherit BroadcastReceiver and override the onReceiver Method
  
             // Use the filter to receive the specified action Broadcast
    
 

The other is dynamic registration. It is registered in a program using Context. registerReceiver. The registered broadcast receiver is equivalent to an anonymous class. Both methods require IntentFIlter.

IntentFilter intentFilter = new IntentFilter (); intentFilter. addAction (String); // specify the action for BroadcastReceiver to receive the broadcast registerReceiver (BroadcastReceiver, intentFilter) of the same action );

GENERAL: Register in onStart and cancel unregisterReceiver in onStop

Specify the broadcast target Action: Intent intent = new Intent (actionString );

Messages can also be carried through Intent: intent. putExtra ("msg", "hello, I sent messages through broadcast ");

Send broadcast message: Context. sendBroadcast (intent)


2. Send broadcast events: Send broadcast events through Context. sendBroadcast. Intent transmits the actions used for registration.

3. Receive broadcast events: When the sent broadcast is listened to by the receiver, it will call its onReceive () method and send the Intent object containing the message to it. The code execution time in onReceive should not exceed 5 s; otherwise, the Android system will pop up a time-out dialog.

Iv. Two types of BroadcastReceiver

1. Normal broadcast Normal broadcasts (sent using Context. sendBroadcast () is completely asynchronous. They all run in an undefined order, usually at the same time. This will be more effective, but it means that the consumer cannot contain the results to be used or the APIs to be aborted.
2. Ordered broadcast Ordered broadcasts (sent using Context. sendOrderedBroadcast () is sent to a receiver each time. The so-called order means that each worker can be propagated to the next worker after execution, or the propagation can be completely aborted without being propagated to other worker workers. The sequence of worker er running can be controlled by android: priority in matched intent-filter. When priority has the same priority, worker er runs in any order.


PS:

The following is an example of broadcast events in four cases: static registration of System broadcast events, static registration of user-defined broadcast events, Dynamic Registration of System broadcast events and Dynamic Registration of user-defined broadcast events.

1. Create a broadcast Receiver

import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyReceiver extends BroadcastReceiver {private static final String TAG = "MyReceiver";@Overridepublic void onReceive(Context context, Intent intent) {String msg = intent.getStringExtra("msg");Log.i(TAG, msg);}}
2. Broadcast Registration

1) static registration
Static registration is configured in the AndroidManifest. xml file, and we will register a broadcast address for MyReceiver:

         
                  
           
          
 
After the above information is configured, as long as it is broadcast of the android. intent. action. MY_BROADCAST address, MyReceiver can receive it.


2) Dynamic Registration
Dynamic Registration requires you to dynamically specify the broadcast address and register it in the Code. Generally, we register a broadcast in Activity or Service. Let's take a look at the registered code:

MyReceiver receiver = new MyReceiver();        IntentFilter filter = new IntentFilter();filter.addAction("android.intent.action.MY_BROADCAST");        registerReceiver(receiver, filter);

3) Send Broadcast

    public void send(View view) {    Intent intent = new Intent("android.intent.action.MY_BROADCAST");    intent.putExtra("msg", "hello receiver.");    sendBroadcast(intent);    }

PS:

The following is a brief introduction to system broadcast.

Below are many standard Broadcast actions defined in the android system to respond to Broadcast events in the system (only part of them are listed)

① ACTION_TIME_CHANGED (triggered when the time changes)
② ACTION_BOOT_COMPLETED (triggered after the system is started)-for example, some programs are started after startup in this way.
③ ACTION_PACKAGE_ADDED (triggered when a package is added)
④ ACTION_BATTERY_CHANGED (triggered when the power is low)

/*** The system statically registers the broadcast message receiver ** @ author zuolongsnail il **/public class SystemReceiver extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {if (intent. getAction (). equals (Intent. ACTION_BATTERY_LOW) {Log. e ("systemcycler", "Low Power prompt"); Toast. makeText (context, "your cell phone is underpowered, please recharge in time", Toast. LENGTH_SHORT ). show ();}}}

 
 
  
   
  
  
  
   
  
 

V,Normal broadcast and ordered Broadcast

The above example is just a receiver to receive broadcasts. If multiple receivers register the same broadcast address, what will happen? Can they receive the same broadcast at the same time, will there be interference between them?

This involves the concepts of normal broadcast and ordered broadcast.

1. Normal Broadcast (Normal Broadcast): Normal Broadcast is completely asynchronous and can be received by all receivers at the same time point (logically). The message transmission efficiency is relatively high. However, the receiver cannot pass the processing result to the next receiver, and cannot terminate Broadcast of Broadcast Intent.

2. Ordered Broadcast (Ordered Broadcast): the receiver of Ordered Broadcast will accept Broadcast in sequence according to the predefined priority. For example, if the level of A is higher than the level of B and B is higher than that of C, Broadcast first passes to A, then to B, and finally to C. Priority levels are stated in In the element's android: priority attribute, the greater the number, the higher the priority level. The value range is-1000-1000. You can also call setPriority () of the IntentFilter object to set the priority level. The receiver of OrderedBroadcast can terminate the spread of Broadcast Intent. Once the spread of BroadcastIntent is terminated, subsequent recipients cannot receive Broadcast. In addition, the receiver of OrderedBroadcast can transmit data to the next receiver. For example, after A obtains Broadcast, it can store data into its result object. When Broadcast passes to B, B can obtain the data stored by A from the result object of.

3. context provides the following two methods for sending broadcasts:
SendBroadcast (): Send Normal Broadcast
SendOrderedBroadcast (): sends OrderedBroadcast.

4. For OrderedBroadcast, the system will execute receivers one by one based on the receiver's priority order of life. The receiver receiving Broadcast preferentially can terminate Broadcast and call the BroadcastReceiver's abortBroadcast () method to terminate Broadcast. If Broadcast is terminated by the previous receiver, the subsequent receiver will no longer be able to obtain Broadcast.

5. In addition, for OrderBroadcast, the receiver receiving Broadcast first can store the processing result in Broadcast through the setResultExtras (Bundle) method, and then pass it to the next receiver. The next receiver uses the Code: bundle bundle = getResultExtras (true) can obtain the data stored by the previous receiver.

Instance: click the button. The two receivers receive the same broadcast and print the data in logcat (in the order of priority of the Receiver, Receiver2 first and Receiver1)

Manifest:

 
     
                          
                                  
               
              
                  
              
                               
           
          
              
                               
           
      
 

Activity Code:

// Send the broadcast, and bind the bundle with the data key a to import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class C48_BroadcastActivity extends Activity {/** Called when the activity is first created. */Button button; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); button = (Button) findViewById (R. id. button); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubIntent intent = new Intent ("com. song.123 "); Bundle bundle = new Bundle (); bundle. putString ("a", "aaa"); intent. putExtras (bundle); // ordered broadcast sendOrderedBroadcast (intent, null );}});}}
Receiver2

Package com. song; // receives broadcast first, and bundle binds data with key B to import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. OS. bundle; public class MyReceiver2 extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// TODO Auto-generated method stubSystem. out. println ("receiver2"); // context. getSystemService (name); Bundle bundle = intent. getExtras (); bundle. putString ("B", "bbb"); System. out. println ("a =" + bundle. get ("a"); setResultExtras (bundle); // cut off broadcast // abortBroadcast ();}}

Receiver1

Package com. song; // receives broadcasts from receiver2, including data import android with key a and key B. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. OS. bundle; public class MyReceiver1 extends BroadcastReceiver {@ Overridepublic void onReceive (Context context, Intent intent) {// TODO Auto-generated method stubSystem. out. println ("receiver1"); // do you want to accept the data Bundle bundle = getResultExtras (true); System. out. println ("a =" + bundle. getString ("a") + ", B =" + bundle. getString ("B "));}}

According to the above configuration, the program includes two receivers, of which Receiver2 is high and Receiver1 is low. If Receiver2zhabortBroadcast () in Receiver2 is commented out, the complete information is displayed in the Receiver1 program.


6. How does the Service interact with BroadcastReceiver?

Previously, we started an Activity and then started the service in the Activity. In this case, you must first start an Activity when starting the service. In many cases, this is redundant. Now we can use the Broadcast handler to run an Activity when the Android system starts. Maybe we will get some inspiration from this. Since we can start the Activity in Broadcast Receiver, why cannot we start the Service? Let's verify this idea.

Write a service class first. This service class is nothing special. You can still use the MyService class written in the previous two sections. The code for configuring the MyService class in the AndroidManifest. xml file is the same.

The following is the most important step to complete: Create a BroadcastReceiver. The Code is as follows:

Import android. content. broadcastReceiver; import android. content. context; import android. content. intent; public class StartupReceiver extends BroadcastReceiver {@ Override public void onReceive (Context context, Intent intent) {// start a Service Intent serviceIntent = new Intent (context, MyService. class); context. startService (serviceIntent); Intent activityIntent = new Intent (context, MessageActivity. class); // to start the Activity in the Service, the following identifier must be set: activityIntent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK); context. startActivity (activityIntent );}}

Two tasks are completed in the onReceive method of the StartupReceiver class: start the service and display an Activity to indicate that the service is successfully started.

Complete AndroidManifest. xml file code.

  
                            
                                    
                
                    
               
                                     
                 
            
           
            
       
   
  


PS:

Automatically run the service at startup

We often have such applications, such as the message PUSH Service, which must be enabled upon startup. To implement this function, we can subscribe to the Broadcast System "BOOT_COMPLETED". After receiving this broadcast, we can start our own services;

The above instance is actually about the same as the startup service. Next we will talk about starting the service.
Aggreger:

public class BootCompleteReceiver extends BroadcastReceiver {private static final String TAG = "BootCompleteReceiver";@Overridepublic void onReceive(Context context, Intent intent) {Intent service = new Intent(context, MsgPushService.class);context.startService(service);Log.i(TAG, "Boot Complete. Starting MsgPushService...");}}


Service:

public class MsgPushService extends Service {private static final String TAG = "MsgPushService";@Overridepublic void onCreate() {super.onCreate();Log.i(TAG, "onCreate called.");}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.i(TAG, "onStartCommand called.");return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent arg0) {return null;}}
AndroidManifest
        
         
         
          
                   
           
          
         
         
 

PS:

Finally, let's talk about the life cycle of Broadcast.

1. A BroadcastReceiver object is valid only when onReceive (Context, Intent) is called. When it is returned from this function, the object is invalid and the lifecycle ends.

Therefore, we can see from this feature that the onReceive (Context, Intent) function called cannot have too many time-consuming operations and cannot be executed using threads. For time-consuming operations, start service. Because BroadcastReceiver may be invalid when other asynchronous operations return results.

2. A Broadcast receiver has only one callback method:

Void onReceive (Context curContext, Intent broadcastMsg)

When the Broadcast receiver receives a Broadcast message, android calls its onReceive () method and passes it to an intent object that contains the Broadcast information. When the Broadcast receiver executes this method, it can be regarded as active. When the onReceive () method returns, it terminates.

A process containing active Broadcast referers is protected by the system to avoid termination. However, if a process does not contain any active components, the system can terminate the process at any time when the memory occupied by the process is used by other processes.

A problem occurs when the response to a broadcast message is very time-consuming and the other thread must execute a task. Imagine if the onReceive () method generates a thread and returns the result, the whole process, including the new thread, will be considered inactive (unless there are other active components in the process ), this process may be terminated by the system. The solution to this problem is to enable a service in the onReceive () method and let the service do that, so that the system will know that there are active components in the process and will not stop the process.


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.