Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

PendingIntent


PendingIntent


Let’s talk a little bit more about PendingIntent. A PendingIntent is a token object. When you get
one here by calling PendingIntent.getService(...), you say to the OS, “Please remember that I want
to send this intent with startService(Intent).” Later on you can call send() on your PendingIntent
token, and the OS will send the intent you originally wrapped up in exactly the way you asked.


The really nice thing about this is that when you give that PendingIntent token to someone else and
they use it, it sends that token as your application. Also, because the PendingIntent itself lives in the
OS, not in the token, you maintain control of it. If you wanted to be cruel, you could give someone else
a PendingIntent object and then immediately cancel it, so that send() does nothing.


If you request a PendingIntent twice with the same intent, you will get the same PendingIntent.
You can use this to test whether a PendingIntent already exists or to cancel a previously issued
PendingIntent.


Managing alarms with PendingIntent


You can only register one alarm for each PendingIntent. That is how setServiceAlarm(Context,
boolean) works when isOn is false: It calls AlarmManager.cancel(PendingIntent) to cancel the
alarm for your PendingIntent and then cancels your PendingIntent.


Because the PendingIntent is also cleaned up when the alarm is canceled, you can check whether
that PendingIntent exists to see whether the alarm is active. This is done by passing in the
PendingIntent.FLAG_NO_CREATE flag to PendingIntent.getService(...). This flag says that if the
PendingIntent does not already exist, return null instead of creating it.


Write a new method called isServiceAlarmOn(Context) that uses PendingIntent.FLAG_NO_CREATE
to tell whether the alarm is on.


Listing 28.10  Adding isServiceAlarmOn() method (PollService.java)


public class PollService extends IntentService {
...
public static void setServiceAlarm(Context context, boolean isOn) {
...
}


public static boolean isServiceAlarmOn(Context context) {
Intent i = PollService.newIntent(context);
PendingIntent pi = PendingIntent
.getService(context, 0, i, PendingIntent.FLAG_NO_CREATE);
return pi != null;
}
...
}


Because this PendingIntent is only used for setting your alarm, a null PendingIntent here means
that your alarm is not set.

Free download pdf