How to Make Widgets on Android

Today, let’s continue the topic of beautiful mobile products called widgets. We already presented to you a list of best Android widgets, now why don’t we explore how to actually make widgets on Android?

Navigation
Starting the Project
Common types of widgets
How to Create a Widget for Android. Step-by-Step
Essentials steps of Android widget development
1. AppWidgetProviderInfo.xml
2. Extending an AppWidgetProvider Class
3. Widget Layout
4. AndroidManifest.xml
5. Margins for Earlier Android Versions
6. App Widget Configuration Activity
7. Widget Updates
Android Widget Checklist

Starting the Project

Widgets are an essential part of our Home and Lock screen customization. They simplify for us the process of accessing certain apps on our devices. If you still don’t have a clue how to find widgets on Android and use these little helpers, check out this quick tutorial. What’s more exciting is that the modern smart- and iPhones couldn’t be imagined without widgets! And here is an excellent opportunity for any developer to make a widget app for Android platform.

As with any development idea, first of all, you should define the concept. What do you want to build exactly? Usually, there are well-known common types of widgets:

  • Information ones – they display an essential info from your app or notify a user (like weather conditions, new emails, or SMS messages).
  • Vertically-scrolling Collection widgets – these show multiple elements from the same group (headlines from news, series of photos).
  • Control widgets – with them customers can activate app’s most important features right from a Home screen (like a remote control for a music application).
  • Hybrid widgets – obviously, such category means combining different elements from other types.

Now, we should proceed with the actual development procedure.

How to Create a Widget for Android. Step-by-Step

All widgets for Android platform have one particular scheme of making. We’ll cover the basics of making a simple widget that could win its place on the user’s Home screen.

What essentials steps you need to go through while developing an Android widget?

  1. In an XML file AppWidgetProviderInfo, there will be all the important info about your widget: dimensions (minimum width and height), layout resource file, regularity of updates, and the presence or absence of Configuration Activity.
  2. Create a BroadcastReceiver – its purpose is to build a user interface of the widget. Then define the methods that you’re going to use to programmatically interact with a widget in the AppWidgetProvider class implementation.
  3. The XML layout resource file will contain widget’s initial layout.
  4. Declaring Widget configuration in the AndroidManifest.xml file.
  5. Don’t forget to implement margins for earlier versions of Android.
  6. 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.
  7. Define the method of the widget updates.
  8. Provide a Preview image for your widget.
  9. Test the product on an actual device!

Keep in mind, that it’s not an established order of your actions. A developer can create these files and classes in any specific line he wants, but it helps when one has a clear idea of how a product would look like before the building process will start.

1. AppWidgetProviderInfo.xml

For defining the AppWidgetProviderInfo object, you have to create a res/xml folder and then create a new XML layout inside this directory. This is going to be our AppWidgetProviderInfo file, so open it and set its root element to <appwidget-provider>. Now specify all the data:

AppWidgetProviderInfo.xml

Some explanation for the used attributes:

  • The minWidth and minHeight specify minimum amount of space that a widget consumes on screen by default. If you want your widget to be portable across multiple devices, the minimum size shouldn’t larger than 4x4.
  • In an updatePeriodMillis, you type (in milliseconds) how often the App Widget framework would request updates from the AppWidgetProvider via the onUpdate() callback method. To conserve the battery, it’s better to update as infrequently as possible.
  • A previewImage presents to the user, well, a preview of how a widget will look like after it's configured. This attribute is reflected in the android:previewImage in a <receiver> element from the AndroidManifest.xml file.
  • The initialLayout simply points to the layout resource of your widget.
  • The optional configure section defines the Activity to launch when a user adds your App Widget and want to configure its properties.
  • A way in which your widget will be resized is specified in the resizeMode attribute. A Home screen widget could be resizable horizontally, vertically, none or on both axes.
  • And the widgetCategory describes whether your App Widget will be placed on the Home screen (home_screen), Lock screen (keyguard), or both. Bear in mind that the home_screen mode is supported only by Android 5.0 and higher.

2. Extending an AppWidgetProvider Class

Here you’ll define the methods that will be called during the widget’s lifecycle. This section is also responsible for the code you’ll create to update a widget. The AppWidgetProvider class extends BroadcastReceiver as a convenience class. It handles only the relevant widget’s event broadcasts (updated, deleted, enabled, disabled). When such events happen, an AppWidgetProvider receives the next method calls:

Method

Description

onUpdate()

1) Called for updates at updatePeriodMillis intervals. 2) And when a user adds the widget, so the essential setup should be performed. However, it’s possible only if you didn’t declare a Configuration Activity, which is responsible for updating sequences.

onAppWidgetOptionsChanged()

Called when the widget is placed in for the first and always it’s resized (starting from Android 4.1).

onDeleted(Context, int[ ])

Called when a widget is deleted from the App Widget host.

onEnabled(Context)

Called an instance the widget is created for the first time.

onDisabled(Context)

Called when the last instance of a widget is removed from the Home screen.

onReceive(Context, Intent)

Called for every broadcast and before each of the above methods. Usually, you don't have to implement this one because the AppWidgetProvider filters by default all broadcasts and calls as appropriate.

So, create a new Java class that extends the AppWidgetProvider class and override its update methods. For example:

Extending an AppWidgetProvider Class

Also, you must declare your AppWidgetProvider class implementation as a broadcast receiver using the <receiver> element in the AndroidManifest. We’ll discuss it later.

3. Widget Layout

Any layout should be nice-looking and correctly functioning across a wide range of different devices. But when it comes to widgets you have to remember that its layout has to be as flexible as possible, however, not stepping out of screen’s boundaries.

So, widget’s layout is defined in the same way as for any Activity: in an XML layout resource file with all the UI elements which a developer wants to use. Yet, there is a major difference – widget layouts are based on RemoteViews, so you have limited options in term of development tools. When you’re creating an Android widget, you can only use the layout classes that are supported by RemoteViews:

And such widget classes:

Anything else is not supported. In addition, RemoteViews also tolerates ViewStub – a zero-sized, invisible View.

4. AndroidManifest.xml

About that  AppWidgetProvider class declaring we mentioned in Step 2. So, it would look like this:

AndroidManifest.xml

An <intent-filter> contains the <action> element with the android:name. It defines that an AppWidgetProvider accepts the ACTION_APPWIDGET_UPDATE broadcast. This is one you have to explicitly declare!

The <meta-data> specifies the AppWidgetProviderInfo resource and requires: 1) android:name for the metadata name. The android.appwidget.provider is used as the AppWidgetProviderInfo descriptor to identify the data. 2) An android:resource defines the AppWidgetProviderInfo resource location.

5. Margins for Earlier Android Versions

As is customary, widgets shouldn’t extend to screen edges and be visually flush with other widgets. Android 4.0 automatically gives widgets a padding between a widget frame and the bounding box for a better alignment with other stuff on user's Home screen. It's easy to code a single layout with custom margins for previous platform’s versions and no extra margins for Android 4.0 and higher. Here is a way.

Margins for Earlier Android Versions

  • Then create 2 dimensions resources: one in res/values/ for the pre-Android 4.0 custom margins, the other in res/values-v14/ for no extra padding for Android 4.0 widgets.

res/values/dimens.xml:

dimensions resources

6. App Widget Configuration Activity

This step is necessary only if you plan to let the users configure some settings after adding your widget. This Activity allows you to play with such available settings as update period, color, size, etc. After the code is done, the App Widget host will automatically launch a Configuration Activity (CA) with the ACTION_APPWIDGET_CONFIGURE action. So, this Activity needs to accept such Intent.

App Widget Configuration Activity

Then, declare it in your AppWidgetProviderInfo file with the android:configure attribute (CSS) like this:

AppWidgetProviderInfo

Keep in mind that when the App Widget host calls the CA it must always return a result that includes App Widget ID. This ID has to be passed by the Intent that launched the Activity (EXTRA_APPWIDGET_ID in the Intent extras).

7. Widget Updates

The first rule says – don’t update too often! In your configuration file, you specify a fixed interval for updates which would be performed automatically (the smallest one is 1800000 milliseconds (30 min)). If the device is asleep at the needed time then it’ll wake up in order to activate updates. Note that the higher update frequency will be the faster a battery will be drained, and you don’t want this to scare off the customers.

There are two general methods to update a widget:

  1. Based on an XML configuration file (using an updatePeriodMillis attribute)
  2. Based on the Android AlarmManager service (for those who have a reason for frequent updates).

Since the first one is more common and easy way, let’s see an example:

Widget Updates

After you set up the widget to respond to the APPWIDGET_UPDATE intent, go on and update your AppWidgetProvider class code. There you’ll specify how often you this calls will be sent and how your widget should deal with these intents when they occur.

Android Widget Checklist

As we mentioned in the beginning, when you build a product you absolutely must test it to see if it works appropriately. Take a couple of devices with different screen configurations and install your App Widget. Check its layout optimization for particular screen size, the view in portrait and landscape mode, and resize parameters. If you find that a widget is acting weird in a certain condition, then you should consider making some changes in your layout or update section. Maybe, you need different minimum size values?

Summing it all up, make sure, you follow this path:

  • Make your widget small but informative. Focus on expanding the broad concept in the app itself.
  • Choose the right widget type and update interval
  • Think through how the content of a resizable widget will adapt to different sizes.
  • Your widget should be orientational and device independent with a flexible layout.

For a more thorough guide on widget making and a code sample, check out this awesome tutorial by JessicaThorns.

How to make widgets on Android - Tecsynt

Read Next

Tutorial: How to Send Push Notifications to Android Device
Tutorial: How to Send Push Notifications to Android Device
Top 5 Mobile Web Browsers for Android Phone
Top 5 Mobile Web Browsers for Android Phone
Awesome Mobile Widgets for Android 
Awesome Mobile Widgets for Android 
Don’t leave us hanging!
[email protected]
Get in Touch