How to create a widget for your Android app

create-an-android-app-widget-feature-image

Android app widgets may look pretty simple – essentially, they’re just small windows that users embed in an App Widget Host, typically their device’s homescreen – but your average application widget has a lot to offer.

For users, widgets help them make the most of all that homescreen real estate that would otherwise go to waste. And for developers, creating a widget to accompany your latest Android app is a way of delivering a better user experience (and if you want those 5 star reviews then you should seize anyopportunity to deliver a better user experience) plus a well-designed app widget is a useful tool for keeping your app at the forefront of the user’s mind.

Every time the user passes through their homescreen, your widget has an opportunity to catch their interest by presenting them with a snippet of your app’s most important content – ideally tempting them into launching your app.
In this article, I’m going to show you how to create an effective app widget for your latest Android project. I’ll be covering all the essentials of creating a basic widget, before sharing some best practices that can help ensure your widget will have no problem securing itself a permanent spot on the user’s homescreen.

Planning your widget

So, you’re sold on the idea of creating an Android app widget, but the first step is deciding what kind of widget you’re going to build.

If you’re struggling for inspiration, then it can help to look at what other Android developers are doing. When you look at all the Android widgets that are currently out there, they can generally be divided into the following categories:

  • Information widgets. Display important information related to your app. Some examples include clock and weather widgets, and widgets that notify the user about new emails or SMS messages.
  • Collection widgets. These vertically-scrolling widgets display multiple elements from the same group, such as a collection of headlines from a news app, or a series of photos from a gallery app.
  • Control widgets. These widgets give users the ability to trigger an app’s most important features from the comfort of their homescreen – kind of like a remote control. A control widget can help your app feel more like an integral part of the user’s device, rather than an add-on that the user opens, plays around with for a while, and then closes. A widget that allows the user to play, pause and skip tracks in a music application is one example of a control widget.
  • Hybrid widgets. Can’t choose between the different categories? Many widgets combine elements from two or more categories – case in point, the music widget from our previous bullet point. Assuming this widget displays some information about the currently-selected track, then this is an example of a control widget that borrows elements from the information widget category. If you do decide to mix and match, then it’s recommended that you target one category first and then add elements from other categories as and when required.
android-widget-hybrid-music-widget-example

An example of an information widget (above) and a hybrid widget (below) that combines elements of a control widget and an information widget.

What are the essential components of an Android widget?

To create a widget, you’ll need the following classes and XML files:

  • An AppWidgetProviderInfo file. An XML file containing important information about your widget, such as its minimum width and height, its layout resource file, how often it should be updated, and whether it uses a configuration Activity.
  • An AppWidgetProvider class implementation. This is where you’ll define the methods that you’ll use to programmatically interact with your widget.
  • An XML layout resource file. Your widget’s initial layout.
  • An App Widget configuration Activity. If you want the user to be able to modify your widget, then you’ll need to create a configuration Activity. This Activity will launch automatically when the user creates an instance of your widget.

There’s no set rules about the order you should create these files and classes in, but I find that it helps to have a clear idea of how your widget will look, before you start worrying about how it’ll function, so I’m going to start by creating my widget’s layout.

Creating your widget’s layout

You define your widget’s layout in the same way you define the layout for any Activity: create an XML layout resource file and add all the UI elements you want to use.

The only major difference is that widget layouts are based on RemoteViews, so you can only use layouts and views that RemoteViews supports.

Specifically, when you’re creating your widget’s layout you can use the following layout classes only:

  • FrameLayout
  • GridLayout
  • LinearLayout
  • RelativeLayout

And you can use the following widget classes only:

  • AdapterViewFlipper
  • AnalogClock
  • Button
  • Chronometer
  • GridView
  • ImageButton
  • ImageView
  • ListView
  • ProgressBar
  • StackView
  • TextView
  • ViewFlipper

Any layout you create should look good and function correctly across a wide range of different screens, however when it comes to widget layouts you have some extra motivation for ensuring you layout is as flexible as possible:

  • Users typically place widgets on their homescreens, and although all Android homescreens are divided into a grid, the exact number of cells, spacing and sizing will vary between devices. Your widget needs to be flexible enough to handle all the different homescreen grids it may encounter.
  • Users expect to be able to resize widgets horizontally and vertically, so your widget should meet these expectations unless it has a very good reason not to. This means your layout needs to be able to cope with however the user chooses to resize your widget.

Creating a flexible widget layout follows many of the best practices you’ll be familiar with from building other Android layouts, but in particular you should:

  • Provide alternate versions of all your layout’s resources. These alternatives should be optimized for a range of different screen configurations. The Android system will then select the best version of each resource to use at runtime, based on the current device.
  • Create a density-independent layout. Make sure you specify all layout dimensions using density-independent pixels (dpi) and use flexible units of measure, such as “wrap_content” and “match_parent,” rather than absolute units.
  • Test! Make sure you test your widget across a range of screen configurations by creating multiple Android Virtual Devices (AVDs). If you do discover issues with a particular screen configuration, then you may want to create an alternate layout that’s optimized for this particular screen. You should also check that your layout can handle being flipped between portrait and landscape mode, and that it continues to look good and function correctly regardless of how the user resizes it. If you do encounter issues once your widget has been shrunk past a certain size, then you can specify a minimum size for your widget – something I’ll be covering when we create our AppWidgetProviderInfo file.

Create an AppWidgetProviderInfo file

The next step is creating a AppWidgetProviderInfo XML file and defining all the qualities you want your widget to have.

Create a res/xml directory (if your project doesn’t contain one already) and then create a new XML layout inside this directory.

android-app-widget-create-xml-directory

This is going to be our AppWidgetProviderInfo file, so open it and set its root element to <appwidget-provider>. You can now specify all the qualifies your widget should possess – here’s a few examples:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
// Your widget’s default width and height
   android:minWidth="50dp"
   android:minHeight="50dp"

// How often your widget should be updated, in milliseconds
  android:updatePeriodMillis="90000000"

// The XML file containing the widget’s layout
   android:initialLayout="@layout/appwidget"

// Whether the user can resize your widget horizontally, vertically, or both (horizontal|vertical). If you don’t
// want your widget to be resizable, then you can set this attribute to "none"
   android:resizeMode="horizontal|vertical"

// Even if you follow all the best practices for designing a flexible layout, if a user keeps shrinking your
// widget indefinitely then at some point it’s going to become unusable. Prevent the user from pushing your
// layout to its breaking point, by assigning it a minimum height and width
   android:minResizeHeight="30dp"
   android:minResizeWidth="30dp"

// Specify whether your widget can be displayed on the homescreen, (home_screen), the lockscreen (keyguard)
// or both - although only devices running Android 4.0 and lower support lockscreen widgets. Lockscreen
// widgets aren’t particularly private, so if you do give the user the option of placing your widget on their
// lockscreen then just make sure your widget doesn’t feature any sensitive or potentially embarrassing
// information!
   android:widgetCategory="home_screen">
</appwidget-provider>

Create Your AppWidgetProvider class

The AppWidgetProvider class is where you’ll define the methods that will be called during the widget’s lifecycle, for example whenever a widget is deleted, enabled or disabled. This class is also where you’ll create the code that’ll ultimately be responsible for updating your widget.Create a new Java class that extends the AppWidgetProvider class and override its update methods. In my example, I’m going to be using MyAppWidgetProvider.

 

[Source:-Android Blog]