This is a follow up tutorial on Android widget. If you haven’t read it till now then please go through    it before starting this tutorial. You may be aware that AppWidgetProvider’s lowest interval is 30 mins. In this tutorial we will learn  to create widget with update interval less than 30 mins using AlarmManager.

New update:

In Android 4.1, a new feature has been introduced for Homescreen widget which enables widget to reorganize its view when resized. To support this feature a new method onAppWidgetOptionsChanged() has been introduced in AppWidgetProvider class. This method gets called in response to the ACTION_APPWIDGET_OPTIONS_CHANGED broadcast when this widget has been layed out at a new size. 

Project Information:  Meta-information about the project.

Platform Version : Android API Level 16.
IDE : Eclipse Helios Service Release 2
Emulator: Android 4.1

Prerequisite: Preliminary knowledge of Android application framework, Intent Broadcast receiver and AlarmManager.

Example with fixed update interval less than 30 mins.

In this tutorial we will create time widget which shows current time. This widget will get updated every second and we will be using AlarmManager for it. Here, repeating alarm is set for one second interval. But in real world scenario, it is not recommended to use one second repeating alarm because it drains the battery fast. You have to follow the similar steps mentioned in previous widget tutorial  to write widget layout file. But this time we are introducing a TextView field in the layout which will display the time. The content of the “time_widget_layout.xml” is given below.
<LinearLayout xmlns:android=""
    android:background="@drawable/widget_background" >

         android:textColor="#000000" />



Follow the same procedure to create the AppWidgetProvider metadata file. The content of metadata file “widget_metadata.xml” is given below.
<appwidget-provider xmlns:android=""
    android:updatePeriodMillis="1800000" >
In this tutorial, onEnabled(), onDsiabled(), onUpdate() and onAppWidgetOptionsChanged() have been defined unlike the previous widget tutorial where only onUpdate() was defined.
  • onEnabled(): An instance of AlarmManager is created here to start the repeating timer and register the intent with the AlarmManager.  As this method gets called at the very first instance of widget installation, it helps to set repeating alarm  only once.
  • onDisabled(): In this method, alarm is canceled because this method gets called as soon as the very last instance of widget is removed/uninstalled and we don’t want to leave the registered alarm even when it’s not being used.
  • onUpdate(): This method updates the time on remote TextView.
  • onAppWidgetOptionsChanged(): This method gets called when the widget is resized.
package com.rakesh.widgetalarmmanagerexample;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.Toast;

public class TimeWidgetProvider extends AppWidgetProvider {

 public void onDeleted(Context context, int[] appWidgetIds) {
  Toast.makeText(context, "TimeWidgetRemoved id(s):"+appWidgetIds, Toast.LENGTH_SHORT).show();
  super.onDeleted(context, appWidgetIds);

 public void onDisabled(Context context) {
  Toast.makeText(context, "onDisabled():last widget instance removed", Toast.LENGTH_SHORT).show();
  Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
  PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

 public void onEnabled(Context context) {
  AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
  Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
  PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
  //After after 3 seconds
  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ 1000 * 3, 1000 , pi);

 public void onUpdate(Context context, AppWidgetManager appWidgetManager,
   int[] appWidgetIds) {
  ComponentName thisWidget = new ComponentName(context,

  for (int widgetId : appWidgetManager.getAppWidgetIds(thisWidget)) {

   //Get the remote views
   RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
   // Set the text with the current time.
   remoteViews.setTextViewText(, Utility.getCurrentTime("hh:mm:ss a"));
   appWidgetManager.updateAppWidget(widgetId, remoteViews);

 public void onAppWidgetOptionsChanged(Context context,
   AppWidgetManager appWidgetManager, int appWidgetId,
   Bundle newOptions) {
  //Do some operation here, once you see that the widget has change its size or position.
  Toast.makeText(context, "onAppWidgetOptionsChanged() called", Toast.LENGTH_SHORT).show();
Broadcast receiver is defined to handle the intent registered with alarm. This broadcast receiver gets called every second because repeating alarm has been set in the AppWidgetProvider classs for 1 second. Here, onReceive() method has been defined which updates the widget with the current time and getCurrentTime() has been used to get the current time.
package com.rakesh.widgetalarmmanagerexample;

import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.RemoteViews;
import android.widget.Toast;

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {
  PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
  PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
  //Acquire the lock

  //You can do the processing here update the widget/remote views.
  RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
  remoteViews.setTextViewText(, Utility.getCurrentTime("hh:mm:ss a"));
  ComponentName thiswidget = new ComponentName(context, TimeWidgetProvider.class);
  AppWidgetManager manager = AppWidgetManager.getInstance(context);
  manager.updateAppWidget(thiswidget, remoteViews);
  //Release the lock


It’s always a good idea to keep utility methods in some utility class which can be accessed from other packages. getCurrentTime() has been defined in the Uitility class. This method is used in AppWidgetProvider and BroadcastReciever classes.
package com.rakesh.widgetalarmmanagerexample;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Utility {
  public static String getCurrentTime(String timeformat){
      Format formatter = new SimpleDateFormat(timeformat);
         return formatter.format(new Date());

In Android manifest file, we need to include WAKE_LOCK permission because wake lock is used in broadcast receiver. AlarmManagerBroadcastReceiver has been registered as broadcast receiver. Remaining part is simple to understand.

  <manifest android:versioncode="1" android:versionname="1.0"
    <uses-sdk android:minsdkversion="16" android:targetsdkversion="16"/>

<uses-permission android:name="android.permission.WAKE_LOCK"/>
    <application android:icon="@drawable/ic_launcher"
        <activity android:label="@string/title_activity_widget_alarm_manager"
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
        <receiver android:icon="@drawable/ic_launcher"
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            <meta-data android:name="android.appwidget.provider"
        <receiver android:name=".AlarmManagerBroadcastReceiver"/>
Once the code is executed, the widget gets registered. When you install widget on homescreen, it appears as shown below.
Android Homescreen time widget

you can download source code from here.

Related tutorial:

Your valuable comments are always welcomed. It will help to improve my post and understanding.

“By three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest.”
By : Confucius

, ,

10 comments untill now

  1. superb…..10 out of 10 from me.step by step explanation

  2. really like it. is a good base example for my needs.

    I noticed a small mistake. You wrote // after 3 seconds, but used 100 * 3, what is actually a 0.3 second.

  3. Thanks Seta for your comment ,
    It was a typo. I have fixed the code.

  4. Good example!, it really helped me a lot! thanks .

  5. well done great tutorial and code,was using widgets but all other code failed due to bugs but this code is amazing – worked very well for me ,using it in a free clock app now ,cheers….

  6. Thanks for the example. Sure is a shame that all the examples found on this topic include the text: But in real world scenario, it is not recommended to use….

  7. Suprrbbbb….Thanks for sharing :)

  8. Elison Niven @ 2013-06-18 00:06

    Thanks for the tutorial. But I do not understand from where the widget is getting updated.

    updateAppWidget is called from 2 places :

    1) appWidgetManager.updateAppWidget(widgetId, remoteViews) in TimeWidgetProvider.onUpdate : Here there is a loop for all the widgets

    2) manager.updateAppWidget(thiswidget, remoteViews) in AlarmManagerBroadcastReceiver.OnReceive : Here there is no loop for all widgets.

    Why is it required to call updateAppWidget from 2 different places?

  9. @Elison Niven Good catch.
    TimeWidgetProvider.onUpdate get called in response to the ACTION_APPWIDGET_UPDATE broadcast when this AppWidget provider is being asked to provide RemoteViews for a set of AppWidgets. Where as AlarmManagerBroadcastReceiver.OnReceive is called whenever AlarmManager triggers an intent. In this particular example, we need to update the time whenever we receive Intent from AlarmManager and this was the best place to update the RemoteView. Ideally I should have called updateAppWidget() in the loop for all instance of Widget in this method but I avoided it.
    Hope I answered your question.

  10. Hoteluri Timisoara Ieftine @ 2014-06-16 13:11

    Pensiuni Brasov Centru

    Hey there terrific blog! Does running a blog such
    as this require a massive amount work? I have very little understanding of coding but I
    was hoping to start my own blog in the near future. Anyway, if you have any suggestions or techniques for new blog owners please share.
    I know this is off subject but I simply needed to ask.

Add your comment now