Creating And Scheduling Alarms Using AlarmManager In Android

Introduction

 
According to Google's Android Doc, "Alarms (based on the AlarmManager class) give you a way to perform time-based operations outside the lifetime of your application".
 
An example can be thought of as downloading the weather report once in a day or twice in a day and notifying the user.
 

Characteristics of Alarms

  • Alarms can let one fire Intents at set times or in certain time intervals.
  • Alarms can be used together with the broadcast receiver to notifies the user.
  • Alarms can triggers even if the device falls asleep because they run outside the application.
  • Alarms can be scheduled to a specific sharp time thus reducing system resources by not relying on background services.

Choosing an Alarm Type

  • ELAPSED_REALTIME
     
    Elapsed Time means time including the sleep time from when the device gets booted. It doesn't wake up the device.
     
  • ELAPSED_REALTIME_WAKEUP 
     
    In ELAPSED_REALTIME_WAKEUP it wakes up and fires the pending intent after the specified interval of time has elapsed since device has booted.
  • RTC 
     
    In this case pending intent fired at the specified time but does not wake up the device.
  • RTC_WAKEUP 
     
    In this case, alarms wake up the device to fire the pending intent at the specified time.

Starting Alarm at Particular Time

 
There are many scenarios in which we have to set an alarm and notify the user at a sharp time. So let's have a look to this specific code given below. This piece of code runs as it notifies (vibrate in our case) user at the time mentioned like 14 hrs and at 40 min but it is up to you which time you would prefer.
 
You might set the time at 15 hrs or at any time. We are using the method setInexactRepeating() because repeating the alarm at hourly intervals you can set the interval at two hours and might do a half-day or full-day(INTERVAL_DAY). We are using the AlarmManager.RTC_WAKEUP because if the device is sleeping then it will wake it up.
  1. public void startAlertAtParticularTime() {    
  2.     
  3.         // alarm first vibrate at 14 hrs and 40 min and repeat itself at ONE_HOUR interval    
  4.     
  5.         intent = new Intent(this, MyBroadcastReceiver.class);    
  6.         pendingIntent = PendingIntent.getBroadcast(    
  7.                 this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);    
  8.     
  9.         Calendar calendar = Calendar.getInstance();    
  10.         calendar.setTimeInMillis(System.currentTimeMillis());    
  11.         calendar.set(Calendar.HOUR_OF_DAY, 14);    
  12.         calendar.set(Calendar.MINUTE, 40);    
  13.     
  14.         alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);    
  15.     
  16.         alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),    
  17.                 AlarmManager.INTERVAL_HOUR, pendingIntent);    
  18.     
  19.         Toast.makeText(this"Alarm will vibrate at time specified",    
  20.                 Toast.LENGTH_SHORT).show();    
  21.     
  22.     }   
 
The above part of code is just to show how to fire the intent at a particular time now we will see the entire code of MainActivity.java and in this case we will set alarms by the time provided by the user in seconds and thereafter repeat it every 10 seconds.
  1. package com.example.gkumar.alarmwithbroadcastreceiver;    
  2.     
  3. import android.app.AlarmManager;    
  4. import android.app.PendingIntent;    
  5. import android.content.Intent;    
  6. import android.support.v7.app.AppCompatActivity;    
  7. import android.os.Bundle;    
  8. import android.view.View;    
  9. import android.widget.Button;    
  10. import android.widget.EditText;    
  11. import android.widget.Toast;    
  12.     
  13. import java.util.Calendar;    
  14.     
  15. public class MainActivity extends AppCompatActivity implements View.OnClickListener {    
  16.     Button alarmbutton, cancelButton;    
  17.     EditText text;    
  18.     PendingIntent pendingIntent;    
  19.     AlarmManager alarmManager;    
  20.     Intent intent;    
  21.     
  22.     @Override    
  23.     protected void onCreate(Bundle savedInstanceState) {    
  24.         super.onCreate(savedInstanceState);    
  25.         setContentView(R.layout.activity_main);    
  26.         alarmbutton = (Button) findViewById(R.id.button);    
  27.         cancelButton = (Button) findViewById(R.id.button2);    
  28.         text = (EditText) findViewById(R.id.editText);    
  29.         alarmbutton.setOnClickListener(this);    
  30.         cancelButton.setOnClickListener(this);    
  31.     
  32.         /* use this method if you want to start Alarm at particular time*/    
  33.     
  34.            // startAlertAtParticularTime();    
  35.     
  36.     }    
  37.     
  38.     // This method to be called at Start button click and set repeating at every 10 seconds interval    
  39.     
  40.     public void startAlert(View view) {    
  41.         if (!text.getText().toString().equals("")) {    
  42.             int i = Integer.parseInt(text.getText().toString());    
  43.             intent = new Intent(this, MyBroadcastReceiver.class);    
  44.             pendingIntent = PendingIntent.getBroadcast(    
  45.                     this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);    
  46.             alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);    
  47.             alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + (i * 1000), 10000    
  48.                     , pendingIntent);    
  49.     
  50.             Toast.makeText(this"Alarm will set in " + i + " seconds",    
  51.                     Toast.LENGTH_LONG).show();    
  52.         }else {    
  53.             Toast.makeText(this,"Please Provide time ",Toast.LENGTH_SHORT).show();    
  54.         }    
  55.     
  56.     }    
  57.     
  58.     public void startAlertAtParticularTime() {    
  59.     
  60.         // alarm first vibrate at 14 hrs and 40 min and repeat itself at ONE_HOUR interval    
  61.     
  62.         intent = new Intent(this, MyBroadcastReceiver.class);    
  63.         pendingIntent = PendingIntent.getBroadcast(    
  64.                 this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);    
  65.     
  66.         Calendar calendar = Calendar.getInstance();    
  67.         calendar.setTimeInMillis(System.currentTimeMillis());    
  68.         calendar.set(Calendar.HOUR_OF_DAY, 14);    
  69.         calendar.set(Calendar.MINUTE, 40);    
  70.     
  71.         alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);    
  72.     
  73.         alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),    
  74.                 AlarmManager.INTERVAL_HOUR, pendingIntent);    
  75.     
  76.         Toast.makeText(this"Alarm will vibrate at time specified",    
  77.                 Toast.LENGTH_SHORT).show();    
  78.     
  79.     }    
  80.     
  81.     @Override    
  82.     public void onClick(View v) {    
  83.         if (v.getId() == R.id.button) {    
  84.             startAlert(v);    
  85.         } else {    
  86.             if (alarmManager != null) {    
  87.     
  88.                 alarmManager.cancel(pendingIntent);    
  89.                 Toast.makeText(this"Alarm Disabled !!",Toast.LENGTH_LONG).show();    
  90.     
  91.             }    
  92.     
  93.         }    
  94.     }    
  95.     
  96.     @Override    
  97.     protected void onStop() {    
  98.         super.onStop();    
  99.         if (alarmManager != null) {    
  100.             alarmManager.cancel(pendingIntent);    
  101.         }    
  102.     }    
  103. }   
Now its time to look around corresponding UI part given below as activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:tools="http://schemas.android.com/tools"    
  4.     android:layout_width="match_parent"    
  5.     android:layout_height="match_parent"    
  6.     android:paddingBottom="@dimen/activity_vertical_margin"    
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"    
  8.     android:paddingRight="@dimen/activity_horizontal_margin"    
  9.     android:paddingTop="@dimen/activity_vertical_margin"    
  10.     tools:context="com.example.gkumar.alarmwithbroadcastreceiver.MainActivity">    
  11.     
  12.     <Button    
  13.         android:layout_width="wrap_content"    
  14.         android:layout_height="wrap_content"    
  15.         android:text="start alarm"    
  16.         android:id="@+id/button"    
  17.         android:layout_below="@+id/editText"    
  18.         android:layout_centerHorizontal="true"    
  19.         android:layout_marginTop="35dp" />    
  20.     
  21.     <EditText    
  22.         android:layout_width="match_parent"    
  23.         android:layout_height="wrap_content"    
  24.         android:inputType="phone"    
  25.         android:hint="Provide Time In Seconds Only"    
  26.         android:id="@+id/editText"    
  27.         android:gravity="center"    
  28.         android:layout_marginTop="50dp"    
  29.         android:layout_below="@+id/textView"    
  30.         android:layout_alignParentRight="true"    
  31.         android:layout_alignParentEnd="true" />    
  32.     
  33.     <TextView    
  34.         android:layout_width="wrap_content"    
  35.         android:layout_height="wrap_content"    
  36.         android:text="Please Enter Time To Set an Alarm"    
  37.         android:id="@+id/textView"    
  38.         android:textSize="20sp"    
  39.         android:layout_alignParentTop="true"    
  40.         android:layout_alignParentLeft="true"    
  41.         android:layout_alignParentStart="true" />    
  42.     
  43.     <Button    
  44.     
  45.         android:layout_width="wrap_content"    
  46.         android:layout_height="wrap_content"    
  47.         android:text="Stop Alarm"    
  48.         android:id="@+id/button2"    
  49.         android:layout_below="@+id/button"    
  50.         android:layout_alignLeft="@+id/button"    
  51.         android:layout_alignStart="@+id/button"    
  52.         android:layout_marginTop="33dp" />    
  53.     
  54. </RelativeLayout>  
Coding the Manifest file and adding permission to vibrate and registering the receiver of name MyBroadcastReceiver as shown in figure.
 
 
Now After Registering a BroadcastReciever that notifies the user whether it means vibrate or executing the alarm as shown in the code below.
  1. package com.example.gkumar.alarmwithbroadcastreceiver;    
  2.     
  3. import android.content.BroadcastReceiver;    
  4. import android.content.Context;    
  5. import android.content.Intent;    
  6. import android.os.Vibrator;    
  7. import android.widget.Toast;    
  8.     
  9. public class MyBroadcastReceiver extends BroadcastReceiver {    
  10.     @Override    
  11.     public void onReceive(Context context, Intent intent) {    
  12.         Toast.makeText(context, "Time Up... Now Vibrating !!!",    
  13.                 Toast.LENGTH_LONG).show();    
  14.         Vibrator vibrator = (Vibrator) context    
  15.                 .getSystemService(Context.VIBRATOR_SERVICE);    
  16.         vibrator.vibrate(2000);    
  17.     }    
  18. }   

Running the Application

 
Starting state
 
When the application runs the first time you will see this image and click on the Start Alarm button.
 
 
Scheduling the Alarm
 
Please enter the time you want to start alarm that is if you entered five say 5 then it will schedule by five seconds.
 
 
Alarm Started 
 
In this case, the alarm starts functioning and vibrating starts and now it repeats after 10 seconds and so on.
 
 
Stopping Alarm 
 
After clicking on the Stop button Alarm gets canceled and stops functioning
 
 

Summary

 
In this article, we have learned how to create and schedule the alarms and notify user via BroadcastReceiver. Selecting first the Alarm type and appropriate methods to start Alarm using AlarmManager class.
 
Read more articles on Android:


Similar Articles