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. // alarm first vibrate at 14 hrs and 40 min and repeat itself at ONE_HOUR interval
  3. intent = new Intent(this, MyBroadcastReceiver.class);
  4. pendingIntent = PendingIntent.getBroadcast(
  5. this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  6. Calendar calendar = Calendar.getInstance();
  7. calendar.setTimeInMillis(System.currentTimeMillis());
  8. calendar.set(Calendar.HOUR_OF_DAY, 14);
  9. calendar.set(Calendar.MINUTE, 40);
  10. alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  11. alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
  12. AlarmManager.INTERVAL_HOUR, pendingIntent);
  13. Toast.makeText(this, "Alarm will vibrate at time specified",
  14. Toast.LENGTH_SHORT).show();
  15. }
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. import android.app.AlarmManager;
  3. import android.app.PendingIntent;
  4. import android.content.Intent;
  5. import android.support.v7.app.AppCompatActivity;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.Toast;
  11. import java.util.Calendar;
  12. public class MainActivity extends AppCompatActivity implements View.OnClickListener {
  13. Button alarmbutton, cancelButton;
  14. EditText text;
  15. PendingIntent pendingIntent;
  16. AlarmManager alarmManager;
  17. Intent intent;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. setContentView(R.layout.activity_main);
  22. alarmbutton = (Button) findViewById(R.id.button);
  23. cancelButton = (Button) findViewById(R.id.button2);
  24. text = (EditText) findViewById(R.id.editText);
  25. alarmbutton.setOnClickListener(this);
  26. cancelButton.setOnClickListener(this);
  27. /* use this method if you want to start Alarm at particular time*/
  28. // startAlertAtParticularTime();
  29. }
  30. // This method to be called at Start button click and set repeating at every 10 seconds interval
  31. public void startAlert(View view) {
  32. if (!text.getText().toString().equals("")) {
  33. int i = Integer.parseInt(text.getText().toString());
  34. intent = new Intent(this, MyBroadcastReceiver.class);
  35. pendingIntent = PendingIntent.getBroadcast(
  36. this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  37. alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  38. alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis() + (i * 1000), 10000
  39. , pendingIntent);
  40. Toast.makeText(this, "Alarm will set in " + i + " seconds",
  41. Toast.LENGTH_LONG).show();
  42. }else {
  43. Toast.makeText(this,"Please Provide time ",Toast.LENGTH_SHORT).show();
  44. }
  45. }
  46. public void startAlertAtParticularTime() {
  47. // alarm first vibrate at 14 hrs and 40 min and repeat itself at ONE_HOUR interval
  48. intent = new Intent(this, MyBroadcastReceiver.class);
  49. pendingIntent = PendingIntent.getBroadcast(
  50. this.getApplicationContext(), 280192, intent, PendingIntent.FLAG_CANCEL_CURRENT);
  51. Calendar calendar = Calendar.getInstance();
  52. calendar.setTimeInMillis(System.currentTimeMillis());
  53. calendar.set(Calendar.HOUR_OF_DAY, 14);
  54. calendar.set(Calendar.MINUTE, 40);
  55. alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
  56. alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
  57. AlarmManager.INTERVAL_HOUR, pendingIntent);
  58. Toast.makeText(this, "Alarm will vibrate at time specified",
  59. Toast.LENGTH_SHORT).show();
  60. }
  61. @Override
  62. public void onClick(View v) {
  63. if (v.getId() == R.id.button) {
  64. startAlert(v);
  65. } else {
  66. if (alarmManager != null) {
  67. alarmManager.cancel(pendingIntent);
  68. Toast.makeText(this, "Alarm Disabled !!",Toast.LENGTH_LONG).show();
  69. }
  70. }
  71. }
  72. @Override
  73. protected void onStop() {
  74. super.onStop();
  75. if (alarmManager != null) {
  76. alarmManager.cancel(pendingIntent);
  77. }
  78. }
  79. }
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. <Button
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="start alarm"
  15. android:id="@+id/button"
  16. android:layout_below="@+id/editText"
  17. android:layout_centerHorizontal="true"
  18. android:layout_marginTop="35dp" />
  19. <EditText
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:inputType="phone"
  23. android:hint="Provide Time In Seconds Only"
  24. android:id="@+id/editText"
  25. android:gravity="center"
  26. android:layout_marginTop="50dp"
  27. android:layout_below="@+id/textView"
  28. android:layout_alignParentRight="true"
  29. android:layout_alignParentEnd="true" />
  30. <TextView
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:text="Please Enter Time To Set an Alarm"
  34. android:id="@+id/textView"
  35. android:textSize="20sp"
  36. android:layout_alignParentTop="true"
  37. android:layout_alignParentLeft="true"
  38. android:layout_alignParentStart="true" />
  39. <Button
  40. android:layout_width="wrap_content"
  41. android:layout_height="wrap_content"
  42. android:text="Stop Alarm"
  43. android:id="@+id/button2"
  44. android:layout_below="@+id/button"
  45. android:layout_alignLeft="@+id/button"
  46. android:layout_alignStart="@+id/button"
  47. android:layout_marginTop="33dp" />
  48. </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. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.os.Vibrator;
  6. import android.widget.Toast;
  7. public class MyBroadcastReceiver extends BroadcastReceiver {
  8. @Override
  9. public void onReceive(Context context, Intent intent) {
  10. Toast.makeText(context, "Time Up... Now Vibrating !!!",
  11. Toast.LENGTH_LONG).show();
  12. Vibrator vibrator = (Vibrator) context
  13. .getSystemService(Context.VIBRATOR_SERVICE);
  14. vibrator.vibrate(2000);
  15. }
  16. }

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: