How to make alarm repeat in Android code


Before getting in to repeating alarm visit this page to know how to create alarm.

Repeating Alarm in Android

Creating a repeating alarm is as simple as crating a normal alarm. You merely have to set few properties to make your alarm repeat. AlarmManager, Alarm work outside of our application life cycle, so this can be used as a trigger for many applications even when the application is not in running state.

One of the biggest difference between timer and alarm is, Timer continuously runs in the background wasting the resources. Whereas alarm can save more resource in this scenario.

Android AlarmManager gives us two ways to make repeating alarm.

alarmManager.setRepeating( )
alarmManager.setInexactRepeating( )

setRepeating():
This is used to set exact time for the alarm down to milliseconds. Do we really have to use this? Since this method is more resource consuming, we do not recommend this approach unless it is really necessary.

setInexactRepeating():
This is used to set some predefined time interval for the alarm. Is this better than setRepeating()? This approach consumes less resource, less battery in comparison with the other. So it is recommended to use setInexactRepeating() whenever possible. Android will synchronize multiple in-exact alarms at run time to save resources. Below are the possible values for in-exact repeating; (prior to api level 19)
INTERVAL_DAY
INTERVAL_HALF_DAY
INTERVAL_HOUR
INTERVAL_HALF_HOUR
INTERVAL_FIFTEEN_MINUTES

As mentioned in the Javadoc of setInexactRepeating(); As of API 19, all repeating alarms will be in-exact and subject to batching with other alarms regardless of their stated repeat interval.

In this post we have give code for both approaches; In this example we have used BroadcastReceiver.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.repeatingalarm"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.repeatingalarm.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="MyBroadcastReceiver" >
        </receiver>
    </application>

</manifest>


Layout.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 <EditText
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="28dp"
        android:ems="10"
        android:hint="Number of seconds"
        android:inputType="numberDecimal" />
    <Button

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="95dp"
        android:onClick="startAlert"
        android:text="Make repeat" />

   

</RelativeLayout>


MyBroadcastReceiver java class:

/**
 * 
 */
package com.example.repeatingalarm;

import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * @author Prabu
 *
 */
public class MyBroadcastReceiver  extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
  Toast.makeText(context, new Date().toString(),
    Toast.LENGTH_SHORT).show();
 }
}



Activity java class:
Using setRepeating( )

package com.example.repeatingalarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author Prabu
 *
 */
public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 public void startAlert(View view) {
  EditText text = (EditText) findViewById(R.id.time);
  int i = Integer.parseInt(text.getText().toString());
  Intent intent = new Intent(this, MyBroadcastReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(
    this.getApplicationContext(), 234324243, intent, 0);
  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (i * 1000), (i * 1000), pendingIntent);
  /*alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (i * 1000), 8000, pendingIntent);*/
  Toast.makeText(this, "Starting alarm in " + i + " seconds",
    Toast.LENGTH_LONG).show();
 }

}


Output screenshots:
Output1
Output1
Output2
Output2

Output3
Output3



Using setInexactRepeating( )

package com.example.repeatingalarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

/**
 * @author Prabu
 *
 */
public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 public void startAlert(View view) {
  EditText text = (EditText) findViewById(R.id.time);
  int i = Integer.parseInt(text.getText().toString());
  Intent intent = new Intent(this, MyBroadcastReceiver.class);
  PendingIntent pendingIntent = PendingIntent.getBroadcast(
    this.getApplicationContext(), 234324243, intent, 0);
  AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  /*alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (i * 1000), (i * 1000), pendingIntent);*/
  alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (i * 1000), 8000, pendingIntent);
  Toast.makeText(this, "Starting alarm in " + i + " seconds",
    Toast.LENGTH_LONG).show();
 }

}



Output screenshots:
Output4
Output4

Output5
Output5

Output6
Output6



Please note that above code is just an example for repeating alarm with BroadcastReceiver. We do not mention about stopping the alarm. 


Source code: RepeatingAlarm.zip






Reactions:

2 comments :

  1. First of all thanks for the tutorial
    I have a question, How can I cancel an alarm after setting one?

    ReplyDelete
  2. The batching of alarm made this setRepeating in some scenario.. How do we prevent this bathing of alarms? I want my alarm to run as before they have different schedules not in batch...

    ReplyDelete