Android basics 31: pendingintent

Source: Internet
Author: User
Tags call back

1. Basic Concepts

Intent indicates the intention. Pending indicates the upcoming or coming thing.
The pendingintent class is used to handle upcoming events. For example, in Notification, it is used to jump to a page, but not to jump to the page immediately.

Intent is started in time. Intent disappears with the activity.
Pendingintent can be considered as a packaging of intent. Generally, the pendingintent instance is obtained through getactivity, getbroadcast, and getservice. The current activity cannot start the intent contained in it immediately, instead, intent is called when pendingintent is executed externally. Because pendingintent stores the context of the current app, it gives the external App the ability to execute the intent in pendingintent just like the current app, even if the current app does not exist during execution, the intent can still be executed through the context in pendingintent. You can also process operations performed by intent. Often and alermanger
Used with icationicationmanager.
Intent is generally used to transmit data between activities, sercvice, and broadcastreceiver, while pendingintent is generally used in notification. It can be understood as a delayed execution intent, and pendingintent is a packaging of intent.

2. Example

2.1 notification example

Private void shownotify () {notification notice = new notification (); notice. icon = R. drawable. icon; notice. tickertext = "you have a new message"; notice. defaults = notification. default_sound; notice. when = 10l; // after a delay of 100 ms, the system vibrates for 250 ms. After a pause of 100 ms, the system shakes for 500 ms. // notice. vibrate = new long [] {100,250,100,500}; error? // Notice. setlatesteventinfo (this, "notification", "meeting", pendingintent. getactivity (this, 0, null, 0); notice. setlatesteventinfo (this, "notification", "meeting", pendingintent. getactivity (this, 0, new intent (this, activity2.class), 0); // you are about to jump to the page. You have not jumped to icationicationmanager manager = (icationicationmanager) getsystemservice (this. notification_service); manager. notify (0, notice );}

2.1 example of text message sending

String MSG = "Hello, beautiful girl"; string number = "135 *** 6784"; smsmanager SMS = smsmanager. getdefault (); pendingintent Pi = pendingintent. getbroadcast (smsactivity. this, 0, new intent (...), 0); SMS. sendtextmessage (number, null, MSG, PI, null); toast. maketext (smsactivity. this, "sent successfully", toast. lenght_long ). show ();

Pendingintent is an intent description. We can give this description to other programs, other programs will do what you want to do at the rest of the time according to this description (by giving a pendingintent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself, it is equivalent to pendingintent representing the intent ). In this example, other programs send text messages. After the messages are sent successfully, broadcast intent.
.
Description of parameters in the smsmanager. sendtextmessage (string destinationaddress, string scaddress, string text, pendingintent sentintent, pendingintent deliveryintent) function:
1) pendingintent sentintent: if the message is sent successfully, sendintent broadcasts the intent of its internal description. Otherwise, an error code is generated and sent to Android. app. pendingintent. onfinished callback. It is best not to leave this parameter blank, otherwise there may be potential problems of resource waste;
2) pendingintent deliveryintent: The pendingintent broadcast that is performed after the message has been delivered to the recipient.
View the pendingintent class. You can see many send functions, that is, pendingintent is performing related operations.

3. Execution Process of pendingintent

Take alarm service as an example:
1. The activity requests an alarm and generally does this:
# // Create a pendingintent
# Intent = new intent (alarm_alert_action );
# Intent. putextra (ID, ID );
# Intent. putextra (time, attimeinmillis );
# Pendingintent sender = pendingintent. getbroadcast (
# Context, 0, intent, pendingintent. flag_cancel_current );
# // Obtain alarmmnager and register a new alarm,
# // Set one-time alert
#
# Alarmmanager AM = (alarmmanager) getsystemservice (alarm_service );
# Am. Set (alarmmanager. power_off_wakeup, attimeinmillis, Sender );
2. alarmmanager. Set calls alarmmanagerservice. Set
3. The core code of alarmmanagerservice. Set is as follows:

We can see that it just saves pendingintent.
4. The alarm Manager Service regularly checks whether alarm has expired. If it has expired, handle it accordingly.
5. alarmthread will call
Alarm. Operation. Send (mcontext, 0,
Mbackgroundintent. putextra (
Intent. extra_alarm_count, alarm. Count ),
Mresultreceiver, mhandler );
That is, execute the intent operation through pendingintent. Send. alarm will send the broadcast of alarm_alert_action.

Note:
1. An important feature of pendingintent is asynchronous processing.
2. Another note is pendingintent. onfinished, which can be used as a parameter of pendingintent. Send,
We know that pendingintent. Send is generally executed in service. After sending is called, onsendfinished of the onfished class is called back, so onsendfinished is generally executed in service.

4. In-depth Analysis

public final class PendingIntent extends Object implements Parcelable

Pendingintent describes intent and its final behavior.

  • You can use the getactivity (context, int requestcode, intent, int flags) series to obtain a pendingintent object for starting an activity from the system,
  • You can use the getservice (context, int requestcode, intent, int flags) method to obtain a pendingintent object for starting a service from the system.
  • You can use the getbroadcast (context, int requestcode, intent, int flags) method to obtain a pendingintent object for broadcast to the intent of broadcastreceiver.

The returned pendingintent can be submitted to another application for further processing. Here, you can process the intent and its final behavior described in pendingintent later.
When you submit pendingintent to another program for processing, pendingintent still has the permission of the original pendingintent Program (with the same permissions and identity ). when you get a pendingintent from the system, you must be very careful. For example, if the intent destination is your own component (activity/service/broadcastreceiver), You 'd better display the specified component name in the intent, to ensure that the intent can reach the destination, otherwise the intent may not know where to send it. A pendingintent is an object reference of a token (node, which should be Linux or C \ c ++) in the Android system. It describes some data that will be used for retrieve (here, the Data describes intent and its final behavior ).
This means that even if the original pendingintent process ends, pendingintent itself still exists and can be used in other processes (other programs submitted by pendingintent. if I extract a pendingintent from the system, and the system has a pendinginent equivalent to the pendingintent you described, the system will directly return a pendingintent with the same token as the pendingintent, instead of a new token and pendingintent. However, when you extract pendingintent, use the flag_cancel_current parameter to remove the old pendingintent's first cancel (). In this way, the pendinginten and its token are new.
With the flag_update_current parameter, the new intent can update the intent object data in the pendingintent, for example, update the extras in the intent. In addition, we can also remove pendingintent's cancel () from the system by calling pendingintent's original process.
Note: Two pendingintents correspond to the same operation, and their intent actions, Data, categories, components, and flags are the same. However, their intent extra can be different.

4.1 main Constants

  • Flag_cancel_current: if an identical pendingintent object already exists in the current system, the existing pendingintent is canceled and a new pendingintent object is generated.
  • Flag_no_create: if the same pendingintent object does not exist in the current system, the system will not create this pendingintent object, but will return NULL directly.
  • Flag_one_shot: This pendingintent only works once. After the pendingintent object is triggered by the send () method, pendingintent will automatically call cancel () for destruction. If you call the send () method again, the system will return a sendintentexception.
  • Flag_update_current: if the system has a pendinginent equivalent to the pendingintent you described, the system uses the pendingintent object, but uses the new intent to update the intent object data in the previous pendingintent, for example, update extras in intent.
4.2 main member functions
  • Getactivities Methods

This series of methods gets a pendingintent object from the system for starting an activity.

public static PendingIntent getActivity (Context context, int requestCode, Intent intent, int flags)

Since: API Level 1
Retrieve a pendingintent that will start a new activity, like calling context. startactivity (intent ). note that the activity will be started outside of the context of an existing activity, so you must use the intent. flag_activity_new_task launch flag in
Intent.
If the startactivity method of context is not called in its subclass (activity), flag_activity_new_task must be added to intent.
For details, refer to the description of startactivity method in context or the basic model of activity and task.

Parameters
Context
The context in which this pendingintent shoshould start the activity.
Requestcode
Private Request Code for the sender (currently not used ).
Intent
Intent of the activity to be launched.
Flags may be flag_one_shot, flag_no_create, flag_cancel_current, flag_update_current, or any of the flags as supported byintent. Fillin () to control which unspecified parts of the intent
That can be supplied when the actual send happens.
When we use the intent. Fillin () method, a data item indicating its intent can be overwritten by the inent parameter of the send method.

Returns
Returns an existing or new pendingintent matching the given parameters. may return NULL only if flag_no_create has been supplied.

public static PendingIntent getActivities (Context context, int requestCode, Intent[] intents, int flags)

Since: API level 11
Like getactivity (context, Int, intent, INT), but allows an array of intents to be supplied. the first intent in the array is taken as the primary key for the pendingintent, like the single intent given to getactivity (context, Int, intent, INT ). upon sending
The resulting pendingintent, all of the intents are started in the same way as they wocould be by passing them to startactivities (intent []).
The first intent in the array will be started outside of the context of an existing activity, so you must use the intent. flag_activity_new_task launch flag in the intent. (activities after the first in the array are started in the context of the previous activity
In the array, so flag_activity_new_task is not needed nor desired for them .)

The last intent in the array represents the key for the pendingintent. in other words, it is the significant element for matching (as done with the single intent given togetactivity (context, Int, intent, INT), its content will be the subject of replacement
By send (context, Int, intent) andflag_update_current, etc. This is because it is the most specific of the supplied intents, And the UI the user actually sees when the intents are started.

Parameters
Context
The context in which this pendingintent shoshould start the activity.
Requestcode
Private Request Code for the sender (currently not used ).
Intents
Array of intents of the activities to be launched.
Flags may be flag_one_shot, flag_no_create, flag_cancel_current, flag_update_current, or any of the flags as supported byintent. Fillin () to control which unspecified parts of the intent
That can be supplied when the actual send happens.
When we use the flags supported by inent. Fillin (), the data items indicating the intent can be overwritten by the intent parameter of the send method.

Returns
Returns an existing or new pendingintent matching the given parameters. may return NULL only if flag_no_create has been supplied.

  • Getservice Method

This method retrieves a pendingintent object used to start a service.

public static PendingIntent getService (Context context, int requestCode, Intent intent, int flags)

Since: API Level 1
Retrieve a pendingintent that will start a service, like calling context. startservice (). The start arguments given to the Service will come from the extras of the intent.

Parameters
Context
The context in which this pendingintent shoshould start the service.
Requestcode
Private Request Code for the sender (currently not used ).
Intent
An intent describing the service to be started.
Flags may be flag_one_shot, flag_no_create, flag_cancel_current, flag_update_current, or any of the flags as supported byintent. Fillin () to control which unspecified parts of the intent
That can be supplied when the actual send happens.
When we use the flags of the intent. Fillin () method, it indicates that the intent data items can be overwritten by the intent parameter of the send method.

Returns
Returns an existing or new pendingintent matching the given parameters. may return NULL only if flag_no_create has been supplied.

  • Getbroadcast Method

This method retrieves a pendingintent object from the system for intent broadcast to broadcastreceiver.

public static PendingIntent getBroadcast (Context context, int requestCode, Intent intent, int flags)

Since: API Level 1
Retrieve a pendingintent that will perform a broadcast, like calling context. sendbroadcast ().

Parameters
Context
The context in which this pendingintent shoshould perform the broadcast.
Requestcode
Private Request Code for the sender (currently not used ).
Intent
The intent to be broadcast.
Flags may be flag_one_shot, flag_no_create, flag_cancel_current, flag_update_current, or any of the flags as supported byintent. Fillin () to control which unspecified parts of the intent
That can be supplied when the actual send happens.
When we use the flags of the intent. Fillin () method, it indicates that the intent data items can be overwritten by the intent parameter of the send method.

Returns
Returns an existing or new pendingintent matching the given parameters. may return NULL only if flag_no_create has been supplied.

  • Send Methods

This series is mainly used to trigger the intent behavior of pendingintent. Use its intent or start an activity, or start a service, or send an intent broadcast to broadcastreceiver.

public void send ()

Since: API Level 1
Perform the operation associated with this pendingintent.
Throws
Pendingintent. canceledexception throws canceledexception if the pendingintent is no longer allowing more intents to be sent through it.

public void send (Context context, int code, Intent intent)

Since: API Level 1
Perform the operation associated with this pendingintent, allowing the caller to specify information about the intent to use.
Parameters
Context
The context of the caller.
This parameter is required only for the intent parameter. If your intent parameter is not null, this parameter cannot be null.
Code result code to supply back to the pendingintent's target.
Intent additional intent data. See intent. Fillin () for information on how this is applied to the original intent.
Throws
Pendingintent. canceledexception throws canceledexception if the pendingintent is no longer allowing more intents to be sent through it.

public void send (int code, PendingIntent.OnFinished onFinished, Handler handler)

Since: API Level 1
Perform the operation associated with this pendingintent, allowing the caller to be notified when the send has completed.
Parameters
Code result code to supply back to the pendingintent's target.
Onfinished the object to call back on when the send has completed, or NULL for no callback.
With this parameter, we can set the callback function after intent is successfully sent.
Handler handler identifying the thread on which the callback shold happen. If null, the callback will happen from the thread pool of the process.
Specifies the handler in which the callback function specified by the onfinished parameter is called.
Throws
Pendingintent. canceledexception throws canceledexception if the pendingintent is no longer allowing more intents to be sent through it.

public void send (Context context, int code, Intent intent, PendingIntent.OnFinished onFinished, Handler handler)

Since: API Level 1
Perform the operation associated with this pendingintent, allowing the caller to specify information about the intent to use and be notified when the send has completed.
For the intent parameter, a pendingintent often has restrictions on which fields can be supplied here, based on how the pendingintent was retrieved ingetactivity (context, Int, intent, INT), getbroadcast (context, int, intent, INT), or getservice (context, Int,
Intent, INT ).
Parameters
Context The context of the caller. This may be null if intent is also null.
This parameter is provided only because of the intent parameter, which is generally the current context. If your intent parameter is not null, this function cannot be null.
Code result code to supply back to the pendingintent's target.
Intent additional intent data. See intent. Fillin () for information on how this is applied to the original intent. Use null to not modify the original intent.
Onfinished the object to call back on when the send has completed, or NULL for no callback.
With this parameter, we can specify the callback function after intent is successfully sent.
Handler handler identifying the thread on which the callback shold happen. If null, the callback will happen from the thread pool of the process.
This parameter indicates the handler in which the callback function specified by the onfinished parameter will be called.
Throws
Pendingintent. canceledexception throws canceledexception if the pendingintent is no longer allowing more intents to be sent through it.

  • Cancel () function
public void cancel ()

Since: API Level 1
Cancel a currently active pendingintent. Only the original application owning an pendingintent can cancel it.
Only the original pengdingintent application can call cancel () to remove it from the system.
Gettargetpackage () function

public String getTargetPackage ()

Since: API Level 1
Return the package name of the application that created this pendingintent, that is the identity under which you will actually be sending the intent. the returned string is supplied by the system, so that an application can not spoof its package.
Returns
The package name of the pendingintent, or null if there is none associated with it.

References:

Differences between intent and pendingintent

In-depth understanding of Android pendingintent

Pendingintent details

Related Article

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.