Controlling the Service

You now need to start the service from within the App Widget onUpdate() method. You can start a service in one of two ways: either through a call to the Context.startService() method or through a call to the Context.bindService() method. In this case, you use the startService() method by replacing the onUpdate() method with the following code: ©Override public void onUpdate(Context context,

AppWidgetManager appWidgetManager, int[] appWidgetIds) {

Intent serviceIntent = new Intent(context, WidgetUpdateService.class);


When a service has finished, it's a good idea to stop it to free up valuable resources. The App Widget will update only once every three hours. Although you could leave the service around—doing nothing—you might as well stop it until it is needed again. This is accomplished by placing the following call at the end of the run() method of the Thread class you use to perform the background tasks:

if (IWidgetUpdateService.this.stopSelfResult(startId)) { Log.e(DEBUG_TAG, "Failed to stop service");

This call to the stopSelfResult() method tells the service to stop itself and returns whether or not the call was successful. If you don't care about the result, simply call the stopSelf() method instead. This method call is made when the processing is finished within the thread since there is no reason for the service to keep running, as it has no further actions to perform, in this case. The service can be launched again the next time the App Widget updates which, for this App Widget, is after three hours have elapsed.

If the App Widget is removed from its host, such as the Home screen, while an update is taking place, the service will need to be terminated in a different way. To accomplish this, put the following code for the onDeleted() method into the AppWidgetProvider implementation: ©Override public void onDeleted(Context context, int[] appWidgetIds) {

Intent serviceIntent = new Intent(context, WidgetUpdateService.class);


super.onDeleted(context, appWidgetIds);

The call to the stopService() method triggers a call to the onDestroy() method of the Service class implementation, which then attempts to interrupt the thread to stop it.

ByWa ay

The example in this hour is pretty simple. It will work fine for a single instance of the App Widget. However, if you want to support multiple instances of the App Widget running simultaneously, further code is needed to handle the differentiation between instances.

Was this article helpful?

0 0

Post a comment