Handling App Widget User Events

As it stands, the App Widget works but isn't terribly interactive. You don't want it to just display information to the user; you want it to also bring the user back to the application. Another area where the App Widget might be improved is to make it handle slow avatar image downloads gracefully.

App Widgets are displayed through RemoteViews objects and not within the application where they are created. Instead, they are displayed within an App Widget host. This affects the handling of user input. Recall that the list of views that an App Widget supports did not include any user input fields. Basically, the only event that an App Widget supports is a click event.


You may have seen a number of App Widgets, such as the Facebook App Widget, present what look like EditText fields. However, if you click on them to enter text, you'll notice that in all cases, a different UI comes up to actually take the entry. This method is an excellent way to provide advanced controls within the limitations of the App Widget framework.

Because the App Widget isn't displayed in the same process as the application, a new method is needed for getting the click event. The Android SDK provides an

Intent type known as PendingIntent for this purpose. This is an Intent that will basically be sent at a future time and can be sent by another process. To create a PendingIntent, an Intent instance must first be created. Then the PendingIntent is created with some additional information, such as what to do on subsequent uses of the same Intent. That is, the exact same instance could be used, or a new instance could be created. Once the PendingIntent object is created, it can be assigned to the RemoteViews object via a call to the setOnClickPendingIntent() method. You need to add the code for this must before the call to the updateAppWidget() method:

Intent launchAppIntent =

new Intent(context, QuizMenuActivity.class); PendingIntent launchAppPendingIntent =

PendingIntent.getActivity(context, 0, launchAppIntent, PendingIntent. FLAG_UPDATE_CURRENT); remoteView.setOnClickPendingIntent(

R.id.widget_view, launchAppPendingIntent);

The view identifier that the PendingIntent is added to via the call to the setOnClickPendingIntent() method is the RelativeLayout object from the widget.xml layout file. Now when the App Widget is clicked, QuizMenuActivity is launched; this happens to be the normal launch activity of the Been There, Done That! application. (Note that any activity could be launched, such as the high scores, but this one makes the most sense.)

Did you Know?

When you create a dynamic App Widget, individual views could have their own PendingIntent objects assigned. This way, the actions they send cause an updateAppWidget() method call to change the look of the App Widget in response to the click.

0 0

Post a comment