More Home Cooking
Finally, remove all of the code from the onUpdate() implementation in
AppWidget, and replace it with a single call to startService():
package apt.tutorial;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.widget.RemoteViews;
import android.database.sqlite.SQLiteDatabase;
public class AppWidget extends AppWidgetProvider {
@Override
public void onUpdate(Context ctxt,
AppWidgetManager mgr,
int[] appWidgetIds) {
ctxt.startService(new Intent(ctxt, WidgetService.class));
}
}
At this point, if you rebuild and reinstall the project, you will see that things
work as they did before, despite this fairly radical implementation shift.
Step #4: Get Control on Button Clicks
Now, we need to arrange to execute some code when the user presses our
new button. Specifically, we want to simply update the app widget itself, so
we get a new random restaurant.
Since we pulled our updating logic into the WidgetService, we need to have
that button call startService() to request WidgetService to do another
update. However, this is an app widget, so we cannot simply add an
OnClickListener to the button – the button is not in our code, but is in the
home screen, configured via the RemoteViews object.
Instead, we can register a PendingIntent, to tell Android what to do when
the button is clicked.