Explanation of Intent in Android (2) Introduction to using Intent to Broadcast events and Broadcast Receiver

Source: Internet
Author: User

Explanation of Intent in Android (2) Introduction to using Intent to Broadcast events and Broadcast Receiver

The first article explains how to use Intent to start new application components. However, they can also use the sendBroadcast method to anonymously broadcast messages between components.

As a system-level message transmission mechanism, Intent can send structured messages between processes. Therefore, you can implement the Broadcast Receiver to listen to and respond to the Broadcast Intent in the application.

By using Intent to broadcast an event, we can let our developers respond to the event without modifying the original application. Android uses a large number of Broadcast referers to Broadcast system events, such as network connections and SMS notifications.

1. Use Intent to broadcast events

In the Application Component, you can build the Intent you want to broadcast, and then use the sendBroadcast method to send it.

You can set Intent actions, data, and categories so that the Broadcast Receiver can accurately determine their needs. In this scheme, the Intent action string can be used to identify the event to be broadcast, so it should be a unique string that can identify the event. Traditionally, Action strings use the same build method as Java package names, as shown below:

public static final String MY_INTENT_ACTION = "com.happy.demo.test";

If you want to include data in Intent, you can use the data attribute of Intent to specify a URI or include extras to add additional basic values.

2. Use the Broadcast Receiver to listen for broadcasts.

Broadcast Receiver can be used to listen to Broadcast Intent, but you need to register it. You can either use code or manifest in the application. in xml file registration, either way, you need to use an Intent Filter to specify which Intent and data he wants to listen.

For broadcast recipients included in the manifest. xml file, when Intent is broadcasted, the applications do not have to be in the running state to receive it, and they will be automatically started.

To create a new Broadcast Receiver, You need to extend the Broadcast Receiver er Class and override the onReceive Method for your own processing. For example:

package com.happy.demo;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;public class MyBroadcastReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stub}}
When receiving a Broadcast Intent that matches the IntentFilter used when registering the receiver, the onReceive method is executed. The onReceive handler must be completed within five seconds. Otherwise, the Force Close dialog box is displayed.

Generally, the Broadcast Receiver updates the content, starts the Service, updates the Activity UI, or uses Notification Manager to notify users.

3. register the Broadcast Receiver in the code.

Boradcast Receiver that affects the UI of a specific Activity is generally registered in the Code. The Receiver registered in the code will only correspond to the Broadcast Intent when the application components that contain it are running.

When the receiver is used to update the UI element of an Activity, it generally registers the receiver in onResume and unregisters the receiver in onPause. Code:

@Overrideprotected void onResume() {super.onResume();registerReceiver(receiver, filter);}@Overrideprotected void onPause() {super.onPause();unregisterReceiver(receiver);}
4. Register in the manifets. xml file of the application

To include a Broadcast receiver in the mainfets of an application, you can add a Receiver tag to the application node and specify the Class Name of the Broadcast receiver to be registered. The receiver node must contain an intent-filter tag to specify the action string to listen. As follows:

             
                              
          
 
5. Broadcast ordered Intent

When the order in which the Broadcast Receiver receives Intent is very important, especially when the Receiver needs to be able to affect the Broadcast Intent received by the Receiver in the future, the sendOrderedBroadcast method can be used as follows:

String requiredPermission = "com.happy.demo.one";sendOrderedBroadcast(intent, requiredPermission);

When this method is used, Intent will be passed to all registered receivers with the appropriate permissions in priority. You can use the android: priority attribute in manifest. xml to specify its permissions. A greater value indicates a higher priority.

 
             
                              
          
 
A common example of sending ordered broadcast is the Intent that broadcasts want to receive the result data. When using the sendOrderedBroadcast method, you can specify a Receiver that will be placed at the end of the Receiver queue. To ensure that after the Broadacst Receiver er has been processed and modified by the registered ordered Broadcast Receiver, it can also receive the Broadcast Intent.

In this case, it is usually helpful to specify the default value for Intent results, data, and extra that may be modified by any receiver that receives the broadcast before the last receiver is returned. As follows:

sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
6. Broadcast Stick Intent

Stity Intent is a useful variant of Broadcast Intent that saves the value of their last Broadcast and when a new receiver is registered to receive the Broadcast, they will return these values as Intent.

When registerReceiver is called to specify the Intent Filter of a matched Sticy Broadcast Intent, the returned value is the last Intent Broadcast, for example, Broadcast of changes in battery power

7. Local Boradcast Manager

The local Broadcast manager is included in the Android Support Library. Users can easily register Broadcast Inten and send Broadcast Intent messages between components in the program. Because the scope of local broadcast is small, it is more efficient to use it than to send global broadcast. It also ensures that no component outside the application can receive our broadcast Intent, so it is also safe. Similarly, other applications cannot send broadcasts to our receivers, preventing these receivers from becoming security vulnerabilities.

The method for obtaining the Local Broadcast Manager is as follows:

LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getApplicationContext());
Registering a local broadcast receiver is the same as registering a global one. The Code is as follows:

lbm.registerReceiver(receiver, intentFilter);
To send a Local Broadcast Intent, you can use the sendBroadcast method of the Local Boradcast Manager and input the Intent to be Broadcast. As follows:

lbm.sendBroadcast(intent);

8. About Pending Intent

The PendingIntent class provides a mechanism to create Intent that can be triggered by other applications at a later time.

PendingIntent is usually used to encapsulate Intent triggered when a future event is returned, such as a single-host Widget or Notification.

The PendingIntent class provides a static method for building PendingIntent to start Activity Service or broadcast Intent.

PendingIntent.getActivity(context, requestCode, intent, flags);PendingIntent.getService(context, requestCode, intent, flags);PendingIntent.getBroadcast(context, requestCode, intent, flags);
The PendingIntent class contains some static constants that can be used to specify a flag to update or cancel an existing PendingIntent that matches the specified action, or to specify whether the Intent is triggered only once.


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.