How to Develop a Widget for Android Platform

Android widgets are accessible right from the home screen, allowing users to see essential information at a glance. Widgets have been an integral part of the Android operating system since its introduction in 2008. 

For years, widgets were really popular, providing users with great convenience. Even though the popularity of widgets has dropped over the past few years, they’re still widely used. 

Time and weather widgets are a must-have on every Android device, and big tech companies create their own widgets for faster access to their apps. For instance,  LinkedIn, Google Chrome, Gmail, and Spotify widgets provide users with a convenient way to perform basic actions from the home screen. 

To offer more convenience to your users, you can create a widget for your application as well. In this article, we’ll show you how to do it. 

Different widgets

Types of widgets for Android plarform

According to the App Widgets Overview by Google, there are four types of widgets: 

  • Information widgets display information that’s crucial for the user. Examples include weather widgets and the My Day widget. Essentially, the majority of widgets belong to this type. Touching an information widget typically opens the application. 

  • Collection widgets display collections of articles, emails, or pictures. Typically, it's a scrollable widget that takes the user to the app when tapped. A bright example of a collection widget is the Gmail widget, which lets users view emails directly from the home screen.

  • Control widgets offer controls for the main functions of an app. The brightest example of a control non-scrollable widget is the Play Music widget. With the help of this widget, users can pause, play,or skip tracks without opening the Play Music app. 

  • Hybrid widgets combine elements of the other three types of widgets.

Widgets of all types have gesture and size limitations. The only gestures available for widgets are vertical swipe and touch. For the sake of portability, a widget’s minimum size should never be larger than 4x4 cells.

How to make a widget for Android: design

The Android Developers guide gives several tips on designing app widgets: 

  • Allow resizing. Let users resize your widget and create several versions of different sizes. This will allow users to adjust the height and/or width within the constraints of their home screen. 

Widget resizing

  • Display only the most important information. Like front-page stories in a newspaper, widgets should consolidate an app’s main information and lead to detailed information in the app.

  • Include navigation elements. It will be useful to include navigation buttons that update information or lead the user to the app’s home screen or settings.

  • Allow users to pin widgets. Android 8.0 Oreo introduced launchers that allow you to create pinned miniature application shortcuts as well as to pin app widgets to the launcher. Similar to pinned shortcuts, pinned widgets give users access to specific tasks in your app. They’re simple to implement. For more information, read this short guide to pinning widgets

  • Allow widget configuration. Some widgets need to be set up before they work, which allows for maximum customization. Android widgets display their configuration choices right after the widget is dropped into the home screen. It’s recommended not to offer more than three configuration options.

Widget configuration

The complete App Widget Design Guidelines can be found on the Android Developers website.

How to create widget in Android: how to code

To better illustrate how to implement widgets, we’ve created a custom widget in Android for an event countdown timer. This widget displays the time until or since an event and the name of the event itself. We haven't used any framework to develop widgets. Here’s how to build it:

1. Declare an app widget in the manifest file of your Android app. Here's the source code:

<receiver
           android:name=".widget.MainWidgetProvider"
        android:icon="@drawable/ic_launcher"
           android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.appwidget.action.ACTION_WIDGET_RECEIVER" />
            </intent-filter>
            <meta-data
               android:name="android.appwidget.provider"
               android:resource="@xml/lock_screen_widget" />
</receiver>

2. Create a configuration file with metadata in the XML directory. Here we define the qualities of our app widget:

A layout file to let the widget know what it should look like

  • The size of the widget

  • Update interval

  • Resizing possibilities

  • Preview image in the widget menu 

  • Type of the widget — starting from Android 5.0, widgets cannot be placed on the lock screen, so you can create only home screen widgets. 

Here’s how we configured our My Day widget:

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
   android:initialLayout="@layout/widget_days_only_count"
   android:minHeight="@dimen/widget_height"
   android:configure="com.yalantis.myday.activities.MainActivity"
   android:minWidth="@dimen/widget_width"
   android:previewImage="@drawable/widget_preview"
   android:updatePeriodMillis="0" />

Almost all of the attributes in the widget’s configuration are optional and depend on the app itself. As you can see, we didn’t set a resize mode, as our widget doesn’t need to be resized, nor did we configure the update time settings. My Day updates depending on the user’s settings. Therefore, this functionality should be configured differently. How? Keep reading.

3. Implement configuration activity. This activity is launched when a user places the widget on the home screen. The configuration screen is optional. It’s needed when you want to make your widget responsive to a user’s choice of font, pictures, and other elements.

4. Create a WidgetProvider class. This class describes all the widget logic. We recommend redefining the method onUpdate. It describes what happens when the widget is updated.

override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
for (appWidgetId in appWidgetIds) {
updateWidgets(context, appWidgetId)
}
}

In the code above, appWidgetIds is an array of IDs of all the widgets installed on the user’s device. Each app widget has a unique ID, so you can add as many widgets as you want and create new ones. They get deleted together with the app.

As we’ve already mentioned, our app widget updates depend on the user’s settings. To implement this functionality, we create a service that gets launched at a certain time. This time depends on the frequency with which the widget is updated.

My Day users can choose in the app’s settings whether to update the widget every minute, once a month, or even once a year. The widget works locally and doesn’t need an internet connection.

The service itself contains the following code:

class WidgetUpdateService : Service() {

override fun onBind(intent: Intent): IBinder? {
return null
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
updateLockAndHomeWidget()
return START_NOT_STICKY
}

fun updateLockAndHomeWidget() {
val intent = Intent(this, MainWidgetProvider::class.java)
intent.action = SyncStateContract.Constants.IntentActions.WIDGET_UPDATE_ACTION
val ids = AppWidgetManager.getInstance(this)
.getAppWidgetIds(ComponentName(this, MainWidgetProvider::class.java))
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
sendBroadcast(intent)
}
}

The service is launched with the help of AlarmManager:

fun setWidgetService() {
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val pi = PendingIntent.getService(
this, 0, Intent(
this,
WidgetUpdateService::class.java
), PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManager.set(AlarmManager.RTC_WAKEUP, App.sharedPrefManager.getUpdateTime(), pi)
}

5. Create user interface.  There are several limitations that exist in the widget development process. Widget extensions can use only the following UI elements:

  • FrameLayout

  • LinearLayout

  • RelativeLayout

  • GridLayout

  • AnalogClock

  • Button

  • Chronometer

  • ImageButton

  • ImageView

  • ProgressBar

  • TextView

  • ViewFlipper

  • ListView

  • GridView

  • StackView

  • AdapterViewFlipper

However, if you look at our My Day widget, you’ll see that it has a custom font. We used a little hack in order to make it look the way we wanted it to.

private fun buildUpdate(
data: String,
context: Context,
movingPickerManager: MovingPickerManager
): Bitmap {
val layoutInflater = LayoutInflater.from(context)
val linearLayout = layoutInflater.inflate(R.layout.event_name_layout, null) as LinearLayout
val textView = linearLayout.findViewById<View>(R.id.textView) as TextView
textView.setText(movingPickerManager.getSpannedText(data, App.getPickerTextTypeFace()))
linearLayout.measure(
makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
)
linearLayout.layout(
0, 0, linearLayout.measuredWidth,
linearLayout.measuredHeight
)

val bitmap = Bitmap.createBitmap(
linearLayout.measuredWidth,
linearLayout.measuredHeight, Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
linearLayout.background?.draw(canvas)
linearLayout.draw(canvas)
return bitmap
}

What we did is create a separate layout without any connection to the widget. Then we defined the values for this layout and made a bitmap of it. So the Imageview of the widget is actually a bitmap.

6. The widget is ready!

Our Till My Event widget
Implementing this widget takes about eight hours if you have expertise in widget development.

We hope this article was useful for you. If you have any questions regarding widget development or looking for a reliable app widget provider, drop us a line.

4.4/ 5.0
Article rating
38
Reviews
Remember those Facebook reactions? Well, we aren't Facebook but we love reactions too. They can give us valuable insights on how to improve what we're doing. Would you tell us how you feel about this article?
Want to develop a cool Android app?

We can help you

Learn more about our Android expertise

We use cookies to personalize our service and to improve your experience on the website and its subdomains. We also use this information for analytics.