Tutorial details

Android Homescreen Widget with AlarmManager | App Code for Sale | Preview

Android Homescreen Widget with AlarmManager | Android Tutorial

How to create widget with update interval less than 30 mins using AlarmManager

Overview PAGE TOP

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 ACTIONAPPWIDGETOPTIONS_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 “timewidgetlayout.xml” is given below.

01  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02      android:layout_width="match_parent"
03      android:layout_height="match_parent"
04      android:orientation="vertical"
05      android:background="@drawable/widget_background" >
07       <TextView
08           android:id="@+id/tvTime"
09           style="@android:style/TextAppearance.Medium"
10           android:layout_width="match_parent"
11           android:layout_height="match_parent"
12           android:layout_gravity="center"
13           android:layout_margin="4dip"
14           android:gravity="center_horizontal|center_vertical"
15           android:textColor="#000000" />
17  </LinearLayout>

Follow the same procedure to create the AppWidgetProvider metadata file. The content of metadata file ”widget_metadata.xml” is given below.

1   <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
2       android:initialLayout="@layout/time_widget_layout"
3       android:minHeight="40dp"
4       android:minWidth="130dp"
5       android:updatePeriodMillis="1800000" >
6   </appwidget-provider>

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.

    01 package com.rakesh.widgetalarmmanagerexample;
    03 import android.app.AlarmManager;
    04 import android.app.PendingIntent;
    05 import android.appwidget.AppWidgetManager;
    06 import android.appwidget.AppWidgetProvider;
    07 import android.content.ComponentName;
    08 import android.content.Context;
    09 import android.content.Intent;
    10 import android.os.Bundle;
    11 import android.widget.RemoteViews;
    12 import android.widget.Toast;
    14 public class TimeWidgetProvider extends AppWidgetProvider {
    16  @Override
    17  public void onDeleted(Context context, int[] appWidgetIds) {
    18   Toast.makeText(context, "TimeWidgetRemoved id(s):"+appWidgetIds, Toast.LENGTH_SHORT).show();
    19   super.onDeleted(context, appWidgetIds);
    20  }
    22  @Override
    23  public void onDisabled(Context context) {
    24   Toast.makeText(context, "onDisabled():last widget instance removed", Toast.LENGTH_SHORT).show();
    25   Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    26   PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    27   AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    28   alarmManager.cancel(sender);
    29   super.onDisabled(context);
    30  }
    32  @Override
    33  public void onEnabled(Context context) {
    34   super.onEnabled(context);
    35   AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    36   Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    37   PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    38   //After after 3 seconds
    39   am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ 100 * 3, 1000 , pi);
    40  }
    42  @Override
    43  public void onUpdate(Context context, AppWidgetManager appWidgetManager,
    44int[] appWidgetIds) {
    45   ComponentName thisWidget = new ComponentName(context,
    46 TimeWidgetProvider.class);
    48   for (int widgetId : appWidgetManager.getAppWidgetIds(thisWidget)) {
    50//Get the remote views
    51RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
    52  R.layout.time_widget_layout);
    53// Set the text with the current time.
    54remoteViews.setTextViewText(R.id.tvTime, Utility.getCurrentTime("hh:mm:ss a"));
    55appWidgetManager.updateAppWidget(widgetId, remoteViews);
    56   }
    57  }
    59  @Override
    60  public void onAppWidgetOptionsChanged(Context context,
    61AppWidgetManager appWidgetManager, int appWidgetId,
    62Bundle newOptions) {
    63   //Do some operation here, once you see that the widget has change its size or position.
    64   Toast.makeText(context, "onAppWidgetOptionsChanged() called", Toast.LENGTH_SHORT).show();
    65  }
    66 }

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.

01  package com.rakesh.widgetalarmmanagerexample;
03  import android.app.AlarmManager;
04  import android.app.PendingIntent;
05  import android.appwidget.AppWidgetManager;
06  import android.content.BroadcastReceiver;
07  import android.content.ComponentName;
08  import android.content.Context;
09  import android.content.Intent;
10  import android.os.PowerManager;
11  import android.widget.RemoteViews;
12  import android.widget.Toast;
14  public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
16   @Override
17   public void onReceive(Context context, Intent intent) {
18    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
19    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
20    //Acquire the lock
21    wl.acquire();
23    //You can do the processing here update the widget/remote views.
24    RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
25      R.layout.time_widget_layout);
26    remoteViews.setTextViewText(R.id.tvTime, Utility.getCurrentTime("hh:mm:ss a"));
27    ComponentName thiswidget = new ComponentName(context, TimeWidgetProvider.class);
28    AppWidgetManager manager = AppWidgetManager.getInstance(context);
29    manager.updateAppWidget(thiswidget, remoteViews);
30    //Release the lock
31    wl.release();
32   }
33  }

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.

01  package com.rakesh.widgetalarmmanagerexample;
03  import java.text.Format;
04  import java.text.SimpleDateFormat;
05  import java.util.Date;
07  public class Utility {
08    public static String getCurrentTime(String timeformat){
09        Format formatter = new SimpleDateFormat(timeformat);
10           return formatter.format(new Date());
11       }
12  }

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.

01    <manifest android:versioncode="1" android:versionname="1.0"
02        package="com.rakesh.widgetalarmmanagerexample"
03        xmlns:android="http://schemas.android.com/apk/res/android">
04      <uses-sdk android:minsdkversion="16" android:targetsdkversion="16"/>
06  <uses-permission android:name="android.permission.WAKE_LOCK"/>
07      <application android:icon="@drawable/ic_launcher"
08            android:label="@string/app_name">
09          <activity android:label="@string/title_activity_widget_alarm_manager"
10                  android:name=".WidgetAlarmManagerActivity">
11              <intent-filter>
12                  <action android:name="android.intent.action.MAIN"/>
13                  <category android:name="android.intent.category.LAUNCHER"/>
14              </intent-filter>
15          </activity>
16          <receiver android:icon="@drawable/ic_launcher"
17               android:label="@string/app_name"
18               android:name=".TimeWidgetProvider">
19              <intent-filter>
20                  <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
21              </intent-filter>
22              <meta-data android:name="android.appwidget.provider"
23                  android:resource="@xml/widget_metadata"/>
24          </receiver>
25          <receiver android:name=".AlarmManagerBroadcastReceiver"/>
26      </application>
27  </manifest>

Once the code is executed, the widget gets registered. When you install widget on homescreen, it appears as shown below.


you can download source code from here.

Reference PAGE TOP


0 Comments Leave a comment

Please login in order to leave a comment.

Newest first

to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.