Working with Pending Intents

As I describe in the previous section, the AppWidgetProvider is essentially a translator. It receives a message from the Home screen app widget and responds with a result you specified. The AppWidgetProvider does not work with just any message, though. If you want to receive input from your app widget, you need to use a PendingIntent.

To understand what a PendingIntent is, you need to fully grasp the basic concept of intents and how they work.

Understanding the Android intent system

An Intent object in Android is, well, exactly that: an intent. The best way to think about intents is to envision turning on a light with a light switch. Your intent is to turn on the light, and to do so, you perform the action of flipping the switch to the On position. In Android, this correlates to creating an instance of the Intent class with an Action in it specifying that the light is to be turned on, as shown here:

Intent turnLightOn = new Intent(“TURN_LIGHT_ON”);

You fire this intent into the Android messaging system, where an activity (or various different Activity objects) responds appropriately. (In the event many activities respond, Android lets the user choose which one to use.) In the case of your turnLightOn intent, you could provide code in the form of an activity (named TurnLightOnActivity, which is where the code executes) to respond by turning on the light.

As I mention in Chapter 3, an intent is a message that can carry a wide variety of data describing ...

Get Android™ Tablet Application Development For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.