Tutorial details

Android AlarmManager tutorial | App Code for Sale | Preview

Android AlarmManager tutorial | Android Tutorial

How to use AlarmManager

Overview PAGE TOP

While writing an application, need arises to schedule execution of code in future. You may require AlarmManager to schedule your work at a specified time. AlarmManager accesses to system alarm and schedules the execution of code even when the application is not running.

Project Information: Meta-information about the project. Platform Version : Android API Level 10.

IDE : Eclipse Helios Service Release 2

Emulator: Android 4.1

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

AlarmManager: PAGE TOP

AlarmManager has access to the system alarm services. With the help of AlarmManager you can schedule execution of code in future. AlarmManager object can’t instantiate directly however it can be retrieved by calling Context.getSystemService(Context.ALARM_SERVICE). AlarmManager is always registered with intent. When an alarm goes off, the Intent which has been registered with AlarmManager, is broadcasted by the system automatically. This intent starts the target application if it is not running. It is recommended to use AlarmManager when you want your application code to be run at a specific time, even if your application is not currently running. For other timing operation handler should be used because it is easy to use. Handler is covered in other tutorial.


Check out the AlarmManager documention for more info.

In this tutorial let’s learn to create one-time timer and the repeating timer, and also to cancel the repeating timer. Here timer and alarm have been used interchangeably, but in this tutorial context both of them have the same meaning.

Example Code: PAGE TOP

Let’s create three buttons start repeating timer, cancel repeating timer and one-time timer in the layout file. These buttons are attached with methods i.e startRepeatingTimer, cancelRepeatingTimer and onetimeTimer respecitively. These methods will be defined in the Activity class. The layout file is shown below(activityalarmmanager.xml).

01  <linearlayout android:layout_height='match_parent'
02     android:layout_width='match_parent' android:orientation='vertical'
03     xmlns:android='http://schemas.android.com/apk/res/android'
04     xmlns:tools='http://schemas.android.com/tools'>
06     <button android:id='@+id/btStart' android:layout_height='wrap_content'
07       android:layout_width='match_parent' android:onclick='startRepeatingTimer'
08       android:padding='@dimen/padding_medium' android:text='@string/btStart'  
09       tools:context='.WidgetAlarmManagerActivity'/>
10     <button android:id='@+id/btCancel' android:layout_height='wrap_content'
11       android:layout_width='match_parent' android:onclick='cancelRepeatingTimer' 
12       android:padding='@dimen/padding_medium' android:text='@string/btCancel'
13       tools:context='.WidgetAlarmManagerActivity'/>
14      <button android:id='@+id/btOneTime' android:layout_height='wrap_content'
15      android:layout_width='match_parent' android:onclick='onetimeTimer'
16      android:padding='@dimen/padding_medium' android:text='@string/btOneTime'  
17      tools:context='.WidgetAlarmManagerActivity'/>
18    </linearlayout>

We are going to define the BroadcastReciever which handles the intent registered with AlarmManager. In the given class onReceive() method has been defined. This method gets invoked as soon as intent is received. Once we receive the intent we try to get the extra parameter associated with this intent. This extra parameter is user-defined i.e ONETIME, basically indicates whether this intent was associated with one-time timer or the repeating one. Once the ONETIME parameter value has been extracted, Toast message is displayed accordingly. Helper methods have also been defined, which can be used from other places with the help of objects i.e setAlarm(), cancelAlarm() and onetimeTimer() methods. These methods can also be defined somewhere else to do operation on the timer i.e set, cancel, etc. To keep this tutorial simple, we have defined it in BroadcastReceiver.

setAlarm(): This method sets the repeating alarm by use of setRepeating() method. setRepeating() method needs four arguments:

  1. type of alarm,
  2. trigger time: set it to the current time
  3. interval in milliseconds: in this example we are passing 5 seconds ( 1000 * 5 milliseconds)
  4. pending intent: It will get registered with this alarm. When the alarm gets triggered the pendingIntent will be broadcasted.

cancelAlarm(): This method cancels the previously registered alarm by calling cancel() method. cancel() method takes pendingIntent as an argument. The pendingIntent should be matching one, only then the cancel() method can remove the alarm from the system.

onetimeTimer(): This method creates an one-time alarm. This can be achieved by calling set() method. set() method takes three arguments:

  1. type of alarm
  2. trigger time
  3. pending intent

    01  package com.rakesh.alarmmanagerexample;
    03  import java.text.Format;
    04  import java.text.SimpleDateFormat;
    05  import java.util.Date;
    07  import android.app.AlarmManager;
    08  import android.app.PendingIntent;
    09  import android.content.BroadcastReceiver;
    10  import android.content.Context;
    11  import android.content.Intent;
    12  import android.os.Bundle;
    13  import android.os.PowerManager;
    14  import android.widget.Toast;
    16  public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
    18   final public static String ONE_TIME = 'onetime';
    20   @Override
    21   public void onReceive(Context context, Intent intent) {
    22     PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    23           PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'YOUR TAG');
    24           //Acquire the lock
    25           wl.acquire();
    27           //You can do the processing here.
    28           Bundle extras = intent.getExtras();
    29           StringBuilder msgStr = new StringBuilder();
    31           if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
    32            //Make sure this intent has been sent by the one-time timer button.
    33            msgStr.append('One time Timer : ');
    34           }
    35           Format formatter = new SimpleDateFormat('hh:mm:ss a');
    36           msgStr.append(formatter.format(new Date()));
    38           Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
    40           //Release the lock
    41           wl.release();
    42   }
    44   public void SetAlarm(Context context)
    45      {
    46          AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    47          Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    48          intent.putExtra(ONE_TIME, Boolean.FALSE);
    49          PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    50          //After after 5 seconds
    51          am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
    52      }
    54      public void CancelAlarm(Context context)
    55      {
    56          Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    57          PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    58          AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    59          alarmManager.cancel(sender);
    60      }
    62      public void setOnetimeTimer(Context context){
    63       AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    64          Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
    65          intent.putExtra(ONE_TIME, Boolean.TRUE);
    66          PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
    67          am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
    68      }
    69  }

Given below is the manifest file. Here, WAKE_LOCK permission is required because the wake lock is being used while processing in onReceive() method present in AlarmManagerBroadcastReceiver class. AlarmManagerBroadcastReceiver has been registered as broadcast receiver.

01  <manifest android:versioncode='1' android:versionname='1.0'
02         package='com.rakesh.alarmmanagerexample'
03         xmlns:android='http://schemas.android.com/apk/res/android'>
05     <uses-sdk android:minsdkversion='10' android:targetsdkversion='15'/>
06     <uses-permission android:name='android.permission.WAKE_LOCK'/>
07      <application android:icon='@drawable/ic_launcher'
08         android:label='@string/app_name' android:theme='@style/AppTheme'>
09          <activity android:label='@string/title_activity_alarm_manager'
10             android:name='com.rakesh.alarmmanagerexample.AlarmManagerActivity'>
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:name='com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver'>
17          </receiver>
18      </application>
19  </manifest>

Now let’s define the activity class which defines some methods. These methods are going to handle the button clicks. Here in this class we create an instance of AlarmManagerBroadcastReciever which will help us to access setAlarm(), cancelAlarm() and setOnetime(). Rest of the code is easy to understand.

01  package com.rakesh.alarmmanagerexample;
03  import com.rakesh.alarmmanagerexample.R;
04  import android.os.Bundle;
05  import android.app.Activity;
06  import android.content.Context;
07  import android.view.Menu;
08  import android.view.MenuItem;
09  import android.view.View;
10  import android.widget.Toast;
11  import android.support.v4.app.NavUtils;
13  public class AlarmManagerActivity extends Activity {
15   private AlarmManagerBroadcastReceiver alarm;
16      @Override
17      public void onCreate(Bundle savedInstanceState) {
18          super.onCreate(savedInstanceState);
19          setContentView(R.layout.activity_alarm_manager);
20          alarm = new AlarmManagerBroadcastReceiver();
21      }
23      @Override
24   protected void onStart() {
25    super.onStart();
26   }
28      public void startRepeatingTimer(View view) {
29       Context context = this.getApplicationContext();
30       if(alarm != null){
31        alarm.SetAlarm(context);
32       }else{
33        Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
34       }
35      }
37      public void cancelRepeatingTimer(View view){
38       Context context = this.getApplicationContext();
39       if(alarm != null){
40        alarm.CancelAlarm(context);
41       }else{
42        Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
43       }
44      }
46      public void onetimeTimer(View view){
47       Context context = this.getApplicationContext();
48       if(alarm != null){
49        alarm.setOnetimeTimer(context);
50       }else{
51        Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
52       }
53      }
55   @Override
56      public boolean onCreateOptionsMenu(Menu menu) {
57          getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu);
58          return true;
59      }
60  }

Once you are done with the coding, just execute the project and you will find the similar kind of application running in your emulator.

Please download AlarmManagerExample code, if you need reference code.

Happy coding and don’t forget to share!

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.