Using the App WidgetProvider Class

You must declare your AppWidgetProvider class implementation as a broadcast receiver using the <receiver> element in the AndroidManifest (see Declaring an App Widget in the Manifest above).

The AppWidgetProvider class extends BroadcastReceiver as a convenience class to handle the App Widget broadcasts. The AppWidgetProvider receives only the event broadcasts that are relevant to the App Widget, such as when the App Widget is updated, deleted, enabled, and disabled. When these broadcast events occur, the AppWidgetProvider receives the following method calls:

suggest updating as infrequently as possible—perhaps no more than once an hour to conserve the battery. You might also allow the user to adjust the frequency in a configuration—some people might want a stock ticker to update every 15 minutes, or maybe only four times a day.

Note: If the device is asleep when it is time for an update (as defined by updatePeriodMillis), then the device will wake up in order to perform the update. If you don't update more than once per hour, this probably won't cause significant problems for the battery life. If, however, you need to update more frequently and/or you do not need to update while the device is asleep, then you can instead perform updates based on an alarm that will not wake the device. To do so, set an alarm with an Intent that your AppWidgetProvider receives, using the AlarmManager. Set the alarm type to either ELAPSED REALTIME or RTC, which will only deliver the alarm when the device is awake. Then set updatePeriodMillis to zero ("0 ").

• The initialLayout attribute points to the layout resource that defines the App Widget layout.

• The configure attribute defines the Activity to launch when the user adds the App Widget, in order for him or her to configure App Widget properties. This is optional (read Creating an App Widget Configuration Activity below).

See the AppWidgetProviderInfo class for more information on the attributes accepted by the <appwidget-provider> element.

onUpdate(Context, AppWidgetManager, intri)

This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute in the AppWidgetProviderlnfo (seeAdding the AppWidgetProviderlnfo Metadata above). This method is also called when the user adds the App Widget, so it should perform the essential setup, such as define event handlers for Views and start a temporary Service, if necessary. However, if you have declared a configuration Activity, this method is not called when the user adds the App Widget, but is called for the subsequent updates. It is the responsibility of the configuration Activity to perform the first update when configuration is done. (See Creating an App Widget Configuration Activity below.)

onEnabled(Context)

This is called when an instance the App Widget is created for the first time. For example, if the user adds two instances of your App Widget, this is only called the first time. If you need to open a new database or perform other setup that only needs to occur once for all App Widget instances, then this is a good place to do it.

onDisabled(Context)

This is called when the last instance of your App Widget is deleted from the App Widget host. This is where you should clean up any work done in onEnabled(Context), such as delete a temporary database.

onReceive(Context, Intent)

This is called for every broadcast and before each of the above callback methods. You normally don't need to implement this method because the default AppWidgetProvider implementation filters all App Widget broadcasts and calls the above methods as appropriate.

Note: In Android 1.5, there is a known issue in which the onDeleted() method will not be called when it should be. To work around this issue, you can implement onReceive() as described in this Group post to receive the onDeleted() callback.

The most important AppWidgetProvider callback is onUpdated() because it is called when each App Widget is added to a host (unless you use a configuration Activity). If your App Widget accepts any user interaction events, then you need to register the event handlers in this callback. If your App Widget doesn't create temporary files or databases, or perform other work that requires clean-up, then onUpdated() may be the only callback method you need to define. For example, if you want an App Widget with a button that launches an Activity when clicked, you could use the following implementation of AppWidgetProvider:

public class ExampleAppWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

final int N = appWidgetIds.length;

// Perform this loop procedure for each App Widget that belongs to this provider onDeleted(Context, int[1)

onDeleted(Context, int[1)

This is called every time an App Widget is deleted from the App Widget host.

int appWidgetId = appWidgetIds[i];

// Create an Intent to launch ExampleActivity

Intent intent = new Intent(context, ExampleActivity.class);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

// Get the layout for the App Widget and attach an on-click listener to the button

RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget provider layout);

views.setOnClickPendingIntent(R.id.button, pendingIntent);

// Tell the AppWidgetManager to perform an update on the current App Widget appWidgetManager.updateAppWidget(appWidgetId, views);

This AppWidgetProvider defines only the onUpdated() method for the purpose of defining a PendingIntent that launches an Activity and attaching it to the App Widget's button withsetOnClickPendingIntent(int, PendingIntent). Notice that it includes a loop that iterates through each entry in appWidgetIds, which is an array of IDs that identify each App Widget created by this provider. In this way, if the user creates more than one instance of the App Widget, then they are all updated simultaneously. However, only one updatePeriodMillis schedule will be managed for all instances of the App Widget. For example, if the update schedule is defined to be every two hours, and a second instance of the App Widget is added one hour after the first one, then they will both be updated on the period defined by the first one and the second update period will be ignored (they'll both be updated every two hours, not every hour).

Note: Because the AppWidgetProvider is a BroadcastReceiver, your process is not guaranteed to keep running after the callback methods return (see Application Fundamentals > Broadcast Receiver Lifecycle for more information). If your App Widget setup process can take several seconds (perhaps while performing web requests) and you require that your process continues, consider starting a Service in the onUpdated() method. From within the Service, you can perform your own updates to the App Widget without worrying about the AppWidgetProvider closing down due to an Application Not Responding (ANR) error. See the Wiktionary sample's AppWidgetProvider for an example of an App Widget running a Service.

Also see the ExampleAppWidgetProvider.java sample class.

Receiving App Widget broadcast Intents

AppWidgetProvider is just a convenience class. If you would like to receive the App Widget broadcasts directly, you can implement your own BroadcastReceiver or override the onReceive(Context, Intent) callback. The four Intents you need to care about are:

• ACTION APPWIDGET UPDATE

• ACTION APPWIDGET DELETED

• ACTION APPWIDGET ENABLED

• ACTION APPWIDGET DISABLED

Was this article helpful?

0 0

Post a comment