PendingIntent

PendingIntent can be seen as a package of Intent, but it was not immediately perform an action,

But only after certain conditions are met to trigger certain events or perform a specified action.

 

The acquisition PendingIntent

PendingIntent get in three ways: through the Activity Service, BroadcastReceiver get.

1. You can  getActivity (Context context, int requestCode,  Intent intent, int flags) series a way to get from the system used to start an Activity PendingIntent objects.

2. by  getService (Context context, int requestCode,  Intent intent, int flags) method for obtaining a start of a Service PendingIntent object from the system.

3. by getBroadcast (Context context, int requestCode, Intent intent, int flags) method is used to obtain a BroadcastReceiver PendingIntent objects transmitted from the broadcast system.

Description of parameters PendingIntent

Take a third embodiment, the broadcast in the form of instructions

PendingIntent sentIntent = PendingIntent.getBroadcast(this, 0,sIntent, 0);

 

The first parameter is the context.

The second parameter is different from each requestcode, you can produce a plurality Pendingintent.

The third parameter is used to store information.

The fourth parameter is different for marking operation.

getBroadcast (Context context, int requestCode, Intent intent, int flags) of the flags in several states: 


1.FLAG_CANCEL_CURRENT: If AlarmManager management PendingIntent already exists, it will cancel the current PendingIntent, to create a new PendingIntent.

2.FLAG_UPDATE_CURRENT: If AlarmManager management PendingIntent already exists, so the new Intent Intent object data before updating,
such as updating the Intent of Extras, in addition, we can also call cancel PendingIntent in the original process PendingIntent in () from the system to its removed out

3.FLAG_NO_CREATE: If management AlarmManager PendingIntent already exists, then no action will, if not described Intent direct deposit return NULL (blank).

4.FLAG_ONE_SHOT: The PendingIntent effect only once after the trigger method, PendingIntent is called automatically cancel the PendingIntent object through the send () () destruction, then if you then call the send () method will fail if the system will return. a SendIntentException.

Intent is a timely start, activity intent with where vanishes. 
a. Intent is for immediate use, and PendingIntent can wait until after the incident triggered, can PendingIntent the Cancel
b. Intent is terminated after the end of the program, while PendingIntent at the end of the program still valid
c. PendingIntent comes Context, and in need of a Intent a run within the Context
D. in the original task runs in the Intent, PendingIntent run on the new task of

 PendingIntent a real Intent package carrier may be used at the time of departure, according to evoke Intent target component, such as Activity, Service, BroadcastReceiver like.

For example, the general promotion of behavior: receiving a push message background, and displayed on the notification bar when the user clicks the message notification, evoke the specified target :

1 Intent intent = new Intent(action);  
2 PendingIntent pendingIntent = PendingIntent.
3 getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

 

For a one-time act, to achieve the above there is no problem, but for continuous operation, the problem came.

What is the sustained operation? The simplest example is, like the kind of music watercress client displayed on the notification bar, I call it a "remote interaction."

 

As developers, we just need to focus on the model and BackService Notification can be. When the user interaction occurs, the view on the notification triggers the PendingIntent notification bar, and comprising a spread BackService Intent, then depending BackService logic updates the corresponding Notification view, while the PendingIntent new binding, the corresponding code is as follows:

Java code  

 

PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 

PendingIntent.FLAG_UPDATE_CURRENT);  

 

In order to make the new PendingIntent into effect, we specially set Flag to PendingIntent.FLAG_UPDATE_CURRENT , the ok, now that everything is okay.

 

Then we get a little more complicated in the problem, I hope to bring PendingIntent of Intent parameter, like this:

Java code  

1. Intent intent = new Intent(action);  
2. intent.putExtra("data", parcelable);  

 

Then use PendingIntent package, then you go to click on a specific notification -> trigger and trying to get back in the code when good data set, you'll find get to the data in question ---- click on more than secondary when (or click on the first 2+ months notice), the value of data remain unchanged (and the first notification, click the same value for the first time achieved)!

Why?

General, we will select FLAG_UPDATE_CURRENT, direct update PendingIntent currently exist to improve performance. For the meaning FLAG_UPDATE_CURRENT resolution, pointed keep it but its replace its extra data with what is in this new Intent (keep it, but it replaces it with the new additional data intentions), the key point here is the full text ---- PendingIntent in the trap of! ! !

For the literal meaning of the above, if it is determined that a new Intent, the corresponding extra data is updated, but the system determines how new the Intent? Object.equals? Intent.filterEquals ! But from the source code analysis, filrerEquals comparison have the same Action, not the same as the data of Intent must be returns false, then the problem will lie it?

Also missed a parameter: requestCode, but the doc says Shangming: currently not used. Analogy Activity.startActivityForResult (Content content, Class <?> Cls, int resquestCode) informed that the only sign resquestCode also request!

Try the following logic code:

1 Intent intent = new Intent(action);
2 
3  intent.putExtra("data", parcelable);  PendingIntent pendingIntent = 
4 
5 PendingIntent.getService(context, UUID.randomUUID().hashCode(),
6 
7                 intent, PendingIntent.FLAG_UPDATE_CURRENT);

 

 Results speak for themselves ...... In fact, it can be seen from the source to achieve getService little clues:

Java code  

1. public static PendingIntent getService(Context context, int requestCode,  

2.         Intent intent, int flags) {  

3.     String packageName = context.getPackageName();  

4.     String resolvedType = intent != null ? intent.resolveTypeIfNeeded(  

5.             context.getContentResolver()) : null;  

6.     try {  

7.         intent.setAllowFds(false);  

8.         IIntentSender target =  

9.             ActivityManagerNative.getDefault().getIntentSender(  

10.                 ActivityManager.INTENT_SENDER_SERVICE, packageName,  

11.                 null, null, requestCode, new Intent[] { intent },  

12.                 resolvedType != null ? new String[] { resolvedType } : null,  

13.                 flags, null, UserHandle.myUserId());  

14.         return target != null ? new PendingIntent(target) : null;  

15.     } catch (RemoteException e) {  

16.     }  

17.     return null;  

18. }  

 

      PendingIntent is actually a package of IItentSender, it would mean that, when updating PendingIntent, the system should be relatively IIntentSender, since a long list of "structural parameters" point of view, requestCode among them, this relationship is not off.

 

Android status bar notification (Notification)

If you need to see the message, you can drag the status bar to the bottom of the screen to view the message.

step:

1 get notification manager NotificationManager, it is also a system service

2 establishment notification Notification notification = new Notification (icon, null, when);

3 is a new notification setting parameters (such as sound, vibration, flashing lights)

4 added a new notification to the notification manager

Code to send the following message:

// Get the Notification Manager

. 1 the NotificationManager mNotificationManager = 
 2  
. 3  (the NotificationManager) the getSystemService (Context.NOTIFICATION_SERVICE)
 . 4  
. 5  int icon = android.R.drawable.stat_notify_chat;
 . 6  
. 7  Long When = System.currentTimeMillis (); // time of notification of the occurrence of the current system time is
 8  
9  // Create a notification, its icon and title designated 
10  
. 11 the notification notification = new new the notification (icon, null , When); // first parameter icon, the second parameter is a short title prompt, the third notification time 
12 is  
13 is notification.defaults = Notification.DEFAULT_SOUND; // issued default sound
14  
15 notification.flags | = Notification.FLAG_AUTO_CANCEL; // click notification is automatically cleared notification 
16  
. 17 the Intent openintent = new new the Intent ( the this , OtherActivity. Class );
 18 is  
. 19 the PendingIntent contentIntent = PendingIntent.getActivity ( the this , 0, openintent, 0 ); // will be sent when you click on a message to the intent of the system openintent 
20  
21 notification.setLatestEventInfo ( the this , "title", "I am content," contentIntent);
 22  
23 mNotificationManager.notify (0, the Notification); // first notice that uniquely identifies a parameter for the custom

 

Focus is on the last parameter setLatestEventInfo () method! ! ! ! It is a PendingIntent !!!!!!!!!

Used here to PendingIntent (pend intention is undetermined and uncertain meaning)

PendingIntent can be seen on the packaging of Intent. PendingIntent information is mainly held by its current package of Intent and Application of Context. Precisely because PendingIntent in the preservation of the current Application Context, giving it the ability of Intent with his program to be executed, even when executing the current Application does not exist, but also through the presence in the Context PendingIntent still perform Intent.

A good example of PendingIntent:

SmsManager method for transmitting messages:

sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

 

The first argument: destinationAddress mobile phone number

The second parameter: scAddress SMS center number is usually set to null

The third argument: text message content

The fourth parameter: sentIntent determine whether the message is sent successfully, if you do not have a SIM card, or network outages, it can be judged by this itent. Note emphasized that whether the action "send" success. So as to whether they'll get a different matter

The fifth parameter: deliveryIntent time when SMS to the recipient, will receive this deliveryIntent. That highlighted the results of the "send"

That is "successfully sent SMS" and "the other party to receive this message" will activate sentIntent and deliveryIntent both in Intent. This is equivalent to delay the execution of Intent


Two examples above can be understood, Intent PendingIntent that can perform under certain conditions, it is compared to the advantage of their own Intent carries the Context object, so that he would not have to rely on a certain activity can exist.

Examples codes messaging system

private final static String SEND_ACTION      = "send";private final static String DELIVERED_ACTION = "delivered";

private void sendSms(String receiver, String text) {

    SmsManager s = SmsManager.getDefault();

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SEND_ACTION),

                                                      PendingIntent.FLAG_CANCEL_CURRENT);

    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED_ACTION),

                                                           PendingIntent.FLAG_CANCEL_CURRENT);

    // send completed

    registerReceiver(new BroadcastReceiver() {

 

        @Override

        public void onReceive(Context context, Intent intent) {

            switch (getResultCode()) {

                case Activity.RESULT_OK:

                    Toast.makeText(getBaseContext(), "Send Success!", Toast.LENGTH_SHORT).show();

                    break;

                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

                    Toast.makeText(getBaseContext(), "Send Failed because generic failure cause.",

                                   Toast.LENGTH_SHORT).show();

                    break;

                case SmsManager.RESULT_ERROR_NO_SERVICE:

                    Toast.makeText(getBaseContext(), "Send Failed because service is currently unavailable.",

                                   Toast.LENGTH_SHORT).show();

                    break;

                case SmsManager.RESULT_ERROR_NULL_PDU:

                    Toast.makeText(getBaseContext(), "Send Failed because no pdu provided.", Toast.LENGTH_SHORT).show();

                    break;

                case SmsManager.RESULT_ERROR_RADIO_OFF:

                    Toast.makeText(getBaseContext(), "Send Failed because radio was explicitly turned off.",

                                   Toast.LENGTH_SHORT).show();

                    break;

                default:

                    Toast.makeText(getBaseContext(), "Send Failed.", Toast.LENGTH_SHORT).show();

                    break;

            }

        }

    }, new IntentFilter(SEND_ACTION));

 

    // them to accept complete

    registerReceiver(new BroadcastReceiver() {

 

        @Override

        public void onReceive(Context context, Intent intent) {

            switch (getResultCode()) {

                case Activity.RESULT_OK:

                    Toast.makeText(getBaseContext(), "Delivered Success!", Toast.LENGTH_SHORT).show();

                    break;

                default:

                    Toast.makeText(getBaseContext(), "Delivered Failed!", Toast.LENGTH_SHORT).show();

                    break;

            }

        }

    }, new IntentFilter(DELIVERED_ACTION));

 

    // send text messages, sentPI and deliveredPI respectively send them to accept success and the success of SMS is broadcast in

s.sendTextMessage(receiver, null, text, sentPI, delivere

I);

}

When more than two PendingIntent sentPI and deliveredPI were sent successfully and the other party will accept the success in the message is broadcast

API as well as a number of important ways

setResultExtras (Bundle extras)

This function is used to change the current broadcast Extra Additional Information transmitted; it can only be transmitted over a broadcast Context.sendOrderedBroadcast effective; it used to pass any Bundle data, and these data only receivers (details for broadcast) to parse . Of course, it can be set to NULL, so, it places the data from the mapping of all cleared.

parameter:

extras: a new data mapping, can be empty.

When getResultExtras (boolean makeMap) to get additional data parameters passed, as long as not empty, then makeMap whether true and false are able to get the data. Obtain a pass over the setResultExtras (bundle); in the data; and finally re-add data bundle in the data.

Parameters: makemap no big role 

Guess you like

Origin www.cnblogs.com/endv/p/11576121.html