Saturday, April 28, 2012

How to create App Widget in Android?

An App Widget is basically just a BroadcastReceiver that handles specific actions.
Creating a simple App Widget involves several steps:
Create a RemoteView, which provides the user interface for the App Widget.
Tie the RemoteView to an Activity that implements the AppWidgetProvider interface.
Provide key App Widget configuration information in the Android manifest file.
Available views and layouts
A widget is restricted in the elements it can use. For layouts you can use "FrameLayout", "LinearLayout" and "RelativeLayout". As views you can use "AnalogClock", "Button", "Chromometer", "ImageButton", "ImageView", "ProgressBar" and "TextView".
The only interaction with is possible on the views of a widget is via on OnClickListener.
Widget size
A widget will take a certain amount of cells on the homescreen. A cell is usually used to display the icon of one application. As a calculation rule you should define the size of the widget with the formula: ((Number of columns / rows)* 74) - 2. These are device independent pixels and the -2 is used to avoid rounding issues.
Lifecycle method
The AppWidgetProvider interface simplifies handling these actions by providing a framework for developers to implement the following methods:
onEnabled(): Called when the first App Widget is created. Global initialization should take place here, if applicable.
onDisabled(): The inverse of the onEnabled() method, called when the last App Widget handled by this definition is deleted. Global cleanup should take place here, if applicable.
onUpdate(): Called when the App Widget needs to update its View, which could be when the user first creates the widget.
onDeleted(): Called when a particular instance of this App Widget is deleted. Cleanup for the specific instance in question should take place here.
onReceive(): The default implementation of this method handles the BroadcastReceiver actions and makes the appropriate calls to the methods shown above.
For the Android system to know about the App Widget, place a standard <receiver> tag in the Android manifest file.
<receiver android:name="MyWidgetProvider" android:label="Example Widget">
          <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
    <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />

In <receiver> definition, a <meta-data> section references an XML file resource. This file defines addition data for App Widget, corresponding to the AppWidgetProviderInfo class. This attribute specifies that the AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is the only broadcast that you must explicitly declare.
The following code shows the complete widget_info.xml file:
<appwidget-provider xmlns:android=""
    android:minHeight="72dp" android:minWidth="146dp" >

The <appwidget-provider> tag defines the size of the App Widget, the default layout to use, and the configuration Activity to launch whenever an instance of the App Widget is created. To display nicely on the Home screen, widgets must adhere to certain size guidelines.The smallest update interval is 180000 milliseconds (30 minutes). A more flexible update can be archived with the AlarmManager which we will demonstrate later in this tutorial.
Implementing onUpdate()
Update via a service
An App Widget that doesn't display anything isn't very useful. Luckily, the implementation for the RemoteView object of this App Widget is straightforward.
Here we can start service for long running operations or we can set update the App Widget at intervals defined by the updatePeriodMillis attribute.
 RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
        Intent intent = new Intent(context.getApplicationContext(),
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

        // To react to a click we have to use a pending intent as the
        // onClickListener is
        // excecuted by the homescreen application
        PendingIntent pendingIntent = PendingIntent.getService(
                context.getApplicationContext(), 0, intent,
        remoteViews.setOnClickPendingIntent(, pendingIntent);

        // Finally update all widgets with the information about the click
        // listener
        appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

        // Update the widgets via the service
Working with RemoteViews
An App Widget uses a special display control called RemoteViews. Unlike a regular View, a RemoteViews control is designed to display a collection of View controls in another process. Consequently, you can't simply add a button handler because that code would run in your application process, not in the process displaying the RemoteViews object (in this case, the Home Screen process).In order to enable user interaction with a RemoteViews control, you must register for a PendingIntent to be triggered when a specific View within the RemoteViews object is clicked. This is done with a call to the setOnClickPendingIntent() method of the RemoteViews object.
Working with PendingIntents
A PendingIntent is basically a wrapper object combining an Intent with its target action, such as startActivity() or broadcastIntent().
Android services are loosely defined as background processes or executables that can be accessed from other applications. They can be started, to run in the background, or they can be directly connected to by means of a remote interface. On the Service-side of the startService() call is our onStart() handler.In this method we can update widget.
Random random = new Random();

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this

        int[] appWidgetIds = intent
        if (appWidgetIds.length > 0) {
            for (int widgetId : appWidgetIds) {
                int nextInt = random.nextInt(100);
                fakeUpdate = "Random: " + String.valueOf(nextInt);
                RemoteViews remoteViews = new RemoteViews(getPackageName(),
                remoteViews.setTextViewText(, fakeUpdate);
                appWidgetManager.updateAppWidget(widgetId, remoteViews);

Please refer to this given link for more information :[[]]

No comments:

Post a Comment