ZOFTINO.COM android and web dev tutorials

Android App Widget Concepts and Implementation

With android app widgets, users can interact with apps from device home and lock screens. Users can view important information and perform actions using app widgets. App widget code and configuration exists with app code and it is part of app APK for which widget is created. Android system or App widget framework identifies from APK file and adds your app widget to the list of widgets for device on which your app has been installed.

The main idea behind the app widgets is to provide capability for users to have easy access to important data and controls of apps. If your app has frequently changing data or important controls that users need to have quick access to, then your app is a good candidate for providing widget.

Components or elements involved in creating app widget

App widget consists of two parts. First part is UI layout and configuration defined in xml called app widget provider info. Second part is broadcast receiver which handles widget events and is called app widget provider.

In the app widget configuration, you can specify metadata such as, where widget can be placed, home screen or lock screen, widget’s layout, widget’s broadcast receiver and how often the data on widget needs to be refreshed. You can make app widget configurable by letting the user to set properties of widget when user adds app widget. For this, you need to define activity class which handles the configuration event.

Creating app widget

I am going to show all the steps and code involved in creating app widget. The sample widget I am going to create displays one latest coupon and view-all-coupons button. Every hour coupon gets refreshed. Button is assigned a pending intent which takes user to app where all latest coupons can be viewed.

Create layout for your widget

Below is the layout for coupon widget with text view and button. Text view displays latest coupon and button action opens app which shows all latest coupons.

 <FrameLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:padding="8dp"
  android:background="#55000000">>
  <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <TextView
      android:id="@+id/coupon_info"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:layout_weight="1" > </TextView>
    <Button
      android:id="@+id/view_latestcoupons"
      android:layout_width="0dp"
      android:layout_height="match_parent"
      android:text="Latest Coupons" > </Button>
  </LinearLayout>
</FrameLayout>

Defining qualities of app widget

You can definite initial properties of app widget in xml file and save it in res/xml/ folder. Using this xml, system will create AppWidgetProviderInfo metadata object, app widget framework uses this information to display widget and fire broadcast events. The property updatePeriodMillis tells android app widget framework that how often request should be sent to AppWidgetProvider for an update.

 <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="35dp"
    android:minHeight="35dp"
    android:updatePeriodMillis="3600000"
    android:previewImage="@drawable/preview"
    android:initialLayout="@layout/above_layout"
    android:resizeMode="horizontal|vertical"
    android:widgetCategory="home_screen">
</appwidget-provider>

Broadcast receiver AppWidgetProvider

AppWidgetProvider is subclass of BroadcastReceiver which handles broadcast events from app widget. AppWidgetProvider provides call back methods to handle different events, onUpdate(), onDisabled(Context), onEnabled(Context), onDeleted(Context, int[]), onReceive(Context, Intent) and onAppWidgetOptionsChanged().

Resource initiation and clean up can be placed in onDisabled, onEnabled and onDeleted methods. Call back method which refreshes data displayed in widget is onUpdate. This is where you need to fetch latest data from your data source to refresh information in your widget.

Coupon app widget provider onUpdate method gets called on adding the widget to home screen and hourly for coupon refresh.

 public class CouponsAppWidgetProvider extends AppWidgetProvider {
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int nw = appWidgetIds.length;
        for (int i=0; i < nw; i++) {
            int appWidgetId = appWidgetIds[i];
            Intent intent = new Intent(context, ViewCouponsActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.coupon_widget_layout);
            views.setOnClickPendingIntent(R.id.view_latestcoupons, pendingIntent);
            views.setTextViewText(R.id.coupon_info, getLatestCouponForWidget());

            appWidgetManager.updateAppWidget(appWidgetId, views);
        }
    }
} 

Define activity provider as receiver in apps AndroidManifest.xml file.

 <receiver android:name="CouponsAppWidgetProvider" >
    <intent-filter>
        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
               android:resource="@xml/coupon_appwidget_info" />
</receiver>