Thanks to my dear friend Feyza Okumuş

Android Widgets

Eren Utku
Android Bits
Published in
7 min readDec 12, 2016

--

This article covers a complete tutorial about how to add Android Widgets into your application. Understanding the logic and depth diving into Android Widgets with 4 sample projects. You will learn how to code your widget from scratch to advanced. Afterward, at the end article we are going to see what the common mistakes.

Before getting started, what is an Android Widget?

Widgets are an essential aspect of home screen customization. You can imagine them as “at-a-glance” views of an app’s most important data and functionality that is accessible right from the user’s home screen.

You can also read this article in Chinese(中文).

So what we are going to achieved?

  • Widget Creation Steps with a basic example (‘Simple Widget’ — Opening a website on widget clicked)
  • Broadcast Widget Example (‘Broadcast Widget’ — Counting clicks on widget)
  • Configurable Widget Example (‘Configurable Widget’ — Getting data before creation and using the data when it’s clicked)
  • Updating Widget by a Service (‘Updating Widget’ — Updating every minute brings random numbers on widget)

Widget Creation Steps :

  1. create layout for the widget.
  2. create XML for defining the widget properties.
  3. create class for the widget actions.
  4. add all these to AndroidManifest.xml file.

With that knowledge, our first example is a widget that will be opening a website on widget clicks.

Step 1: Creating a very simple layout for a widget.

This layout is displayed as a widget on user’s home-screen.

Step 2: create an XML that defines widget properties.

In res folder create a new XML folder.

Quick look for these properties

  • initialLayout: reference for the widget layout(that we already created).
  • minHeight and minWidth: Every 60dp means 1 cell in android home-screen. For this example, the widget takes min 1x1 cell(s).
  • previewImage: The image that will be shown on android’s widget select screen. We can not draw a layout for preview. We have to set an image.
  • resizeMode: The configuration for resizing the widget.
  • updatePeriodMillis: The widget’s update method is called when the specified time is reached in a millisecond.
  • widgetCategory: home_screen or keyguard.

Android Studio has an amazing interface for creating widgets.

Android Studio - Create a new App Widget

Step 3: Create a class for the widget lifecycle.

AppWidgetProvider extends BroadcastReceiver. SimpleAppWidget is indirectly a child of BroadcastReceiver. So our widget class is a receiver class.

Step 4: Adding into AndroidManifest as a receiver.

Yay! You have implemented a widget for your app :)

Let’s take it to the next level.

RemoteView

Let’s continue with learning RemoteView.

A class that describes a view hierarchy that can be displayed in another process. The hierarchy is inflated from a layout resource file, and this class provides some basic operations for modifying the content of the inflated hierarchy.

RemoteView supports only these layouts:

RemoteView supports only these views:

If you use another view, RemoteView has no operation for the view.

Let’s add some codes to our widget class.

As we can see there is an override method onUpdate which is called every updatePeriodMillis has reached.

See the result:

This example is basic and fast dive for the widget.

Here is the code if you missed something: https://github.com/yerenutku/WidgetExamples/tree/master/SimpleWidgetExample

Understanding Override Methods

Before going to the next example, we need to understand widget classes that override the following methods.

  • onUpdate(): This is called to update the App Widget at intervals defined by the updatePeriodMillis attribute.
  • onAppWidgetOptionsChanged() : This is called when the widget is first placed and also whenever the widget is resized.
  • onDeleted(Context, int[]): This is called every time an App Widget is deleted from the App Widget host.
  • onEnabled(Context): This is called when an instance the App Widget is created for the first time.
  • onDisabled(Context): This is called when the last instance of your App Widget is deleted from the App Widget host.
  • onReceive(Context, Intent): This is called for every broadcast and before each of the above callback methods.

Confused? No problem. Below video shows you when these methods will calls.

Let’s see these fellas in action.

This knowledge gives you full control of on your widget.

Broadcast Widget

We have learned all steps of widget creation. We will not be repeating these steps.

Every click on the widget will send a broadcast and onReceive increases the counter.

In previous example we used .getActivity(), this time we are going to use .getBroadcast().

BroadcastWidget is our widget class. Let’s see what is inside?

Using static fields with widgets is not recommended. But I am trying to make the example as simple as possible. You can use SharedPreferences instead of static fields.

Widget is updating by broadcast.

Here is the result.

Here is the code if you missed something: https://github.com/yerenutku/WidgetExamples/tree/master/BroadcastWidgetExample

You can send whatever you want with broadcast and you can catch the broadcast wherever you want.

Configurable Widgets

Some widgets can be configurable at creation. In this example, we are getting a link from the user and whenever it’s clicked we open this link on the browser.

Create ConfigureActivity for user configuration.

The Basic layout for activity.

In activity’s onCreate method, the first thing we do is setting setResult(RESULT_CANCELED). Why? Android triggers the configure activity that belongs to your widget and awaits result data. If the user did not configure as we expected, let’s say she pressed back button without entering a data, we don’t need to create a widget.

The last thing we do is modify the XML of the widget. With that modification, the Android Operating System will know this widget has configuration activity. So before creating the widget, it will trigger the activity.

As you notice we didn’t talk about widget class yet. We do not need to add any code for widget class because all actions done by ConfigurableWidgetConfigureActivity. But we have to create anyway.

Here is the result.

Here is the code if you missed something: https://github.com/yerenutku/WidgetExamples/tree/master/ConfigurableWidgetExample

Updated By a Service Widget Example

This project will generate random numbers in every minute and displays it on a widget. First of all, we need a service to generate random numbers.

And we have to add this to AndroidManifest.

Service does not start by itself. We need to start the service(in every minute for this example).

But why we do not just use ‘updatePeriodMillis’?

If the device is asleep when it is time for an update (as defined by updatePeriodMillis), then the device will wake up in order to perform the update. If you don't update more than once per hour, this probably won't cause significant problems for the battery life. If, however, you need to update more frequently and/or you do not need to update while the device is asleep, then you can instead perform updates based on an alarm that will not wake the device. To do so, set an alarm with an Intent that your AppWidgetProvider receives, using the AlarmManager. Set the alarm type to either ELAPSED_REALTIME or RTC, which will only deliver the alarm when the device is awake. Then set updatePeriodMillis to zero ("0").

In Previous examples, we used .getActivity() and .getBroadcast() methods. This time we are going to use .getService() method.

The minimum interval time is 60000 millis for AlarmManager. If you need to call your service less than 60 sec with an alarm manager, there are some workarounds like this. But I have to warn you, this action drains the battery and makes users delete your app.

updating widget with random integer values generated by service

Here is the result. I cropped the video to not keep you wait 2 minutes.

Here is the code: https://github.com/yerenutku/WidgetExamples/tree/master/UpdatingWidgetExample

Common questions / mistakes about Widgets

Question:

Programmatically update widget from activity or service

Answer:

Simple, you have to reach your widgets. Afterwards send broadcast that has information about your widgets. See the code below,

Intent intent = new Intent(this, YourWidget.class);
intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
int ids[] = AppWidgetManager.getInstance(getApplication()).getAppWidgetIds(new ComponentName(getApplication(), YourWidget.class));
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
sendBroadcast(intent);

You can see all the answers by: http://stackoverflow.com/questions/3455123/programmatically-update-widget-from-activity-service-receiver

Question:

Every widget instances not doing their job? or doing same job?

Answer:

PendingIntent operations(.getActivity, .getBroadcast etc.) need a parameter requestCode for identification.

You have to set the requestCode with your appWidgetId. With that way, your pending intent becomes unique. Every instance of your widget will use their PendingIntent.

You can see the another question: http://stackoverflow.com/questions/7645949/two-buttons-of-android-widgets-calling-same-activity-with-diffrent-intents

More about Widgets

How the material design should be on widget?

Read further? Helpful links

If you made it at this far, personally thank you for reading. Here is the promised Github link includes whole projects in this article. And feel free for pull requests.

To help others to reach the article don’t forget to recommend 💚. It means a lot to me.

Stay in touch with me via twitter and my website. For more about programming, follow me .

--

--