Setting up alarm using AlarmManager and waking up screen and unlocking keypad on alarm goes off in Android

August 25, 2012

In this article, we will create an Android application which provides a user interface to set an alarm. That user interface will contain datepicker and timepicker widgets. Once this alarm goes off, Android’s AlarmManager starts up an AlertDialog window which is intended to be executed by the alarm.

Suppose the device is in sleep mode while the alarm is going off, then the AlarmManager will switch on the screen and unlock the key pad before starting the intended dialog activity.

This application is developed in Eclipse Classic ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK (R20.0.3 ).

1. Create a new Android application project titled “ServiceAlarmDemo”

Create new Android application project

Figure 1 : Create new Android application project

2. Design application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon

3. Create a blank activity

Create a blank activity

Figure 3 : Create a blank activity

4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details

5. Add Android’s backward compatibility support library

DialogFragment is available from API level 11 ( Honeycomb ) but can be used in pre Honeycomb versions using Android’s support library. Since this application will run in API level 4 and above, we need to add Android Support library to this project to use DialogFramgent in our application.

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup window, Click “Android Tools -> Add Support Library “

6. Update the file res/values/strings.xml


    <string name="app_name">ServiceAlarmDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">Alarm Setting Screen</string>
    <string name="title_activity_demo">Demo Activity Screen</string>
    <string name="str_btn_set_alarm">Set Alarm</string>
    <string name="str_btn_quit">Quit</string>
    <string name="str_tv_message">Opened by Alarm</string>


7. Update the layout file for the MainActivity in the file res/layout/activity_main.xml

<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >









8. Create a DialogFragment class namely AlertDemo in the file src/in/wptrafficanalyzer/servicealarmdemo/

package in.wptrafficanalyzer.servicealarmdemo;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.WindowManager.LayoutParams;

public class AlertDemo extends DialogFragment {

    public Dialog onCreateDialog(Bundle savedInstanceState) {

        /** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
        getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);

        /** Creating a alert dialog builder */
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        /** Setting title for the alert dialog */

        /** Setting the content for the alert dialog */
        builder.setMessage("An Alarm by AlarmManager");

        /** Defining an OK button event listener */
        builder.setPositiveButton("OK", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                /** Exit application on click OK */

        /** Creating the alert dialog window */
        return builder.create();

    /** The application should be exit, if the user presses the back button */
    public void onDestroy() {

9. Create an activity called DemoActivity which is invoked by AlarmManager when an alarm is going off. The DemoActivity class is defined in the file src/in/wptrafficanalyzer/servicealarmdemo/

package in.wptrafficanalyzer.servicealarmdemo;

import android.os.Bundle;
import android.view.WindowManager.LayoutParams;
import android.widget.Toast;

public class DemoActivity extends FragmentActivity {
    protected void onCreate(Bundle savedInstanceState) {

        /** Creating an Alert Dialog Window */
        AlertDemo alert = new AlertDemo();

        /** Opening the Alert Dialog Window. This will be opened when the alarm goes off */, "AlertDemo");

10. Update the MainActivity class in the file src/in/wptrafficanalyzer/servicealarmdemo/

package in.wptrafficanalyzer.servicealarmdemo;

import java.util.GregorianCalendar;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        OnClickListener setClickListener = new OnClickListener() {

            public void onClick(View v) {
                /** This intent invokes the activity DemoActivity, which in turn opens the AlertDialog window */
                Intent i = new Intent("in.wptrafficanalyzer.servicealarmdemo.demoactivity");

                /** Creating a Pending Intent */
                PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);

                /** Getting a reference to the System Service ALARM_SERVICE */
                AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);

                /** Getting a reference to DatePicker object available in the MainActivity */
                DatePicker dpDate = (DatePicker) findViewById(;

                /** Getting a reference to TimePicker object available in the MainActivity */
                TimePicker tpTime = (TimePicker) findViewById(;

                int year = dpDate.getYear();
                int month = dpDate.getMonth();
                int day = dpDate.getDayOfMonth();
                int hour = tpTime.getCurrentHour();
                int minute = tpTime.getCurrentMinute();

                /** Creating a calendar object corresponding to the date and time set by the user */
                GregorianCalendar calendar = new GregorianCalendar(year,month,day, hour, minute);

                /** Converting the date and time in to milliseconds elapsed since epoch */
                long alarm_time = calendar.getTimeInMillis();

                /** Setting an alarm, which invokes the operation at alart_time */
                alarmManager.set(AlarmManager.RTC_WAKEUP  , alarm_time , operation);

                /** Alert is set successfully */
                Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();

        OnClickListener quitClickListener = new OnClickListener() {
            public void onClick(View v) {

        Button btnSetAlarm = ( Button ) findViewById(;

        Button btnQuitAlarm = ( Button ) findViewById(;


    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(, menu);
        return true;

11. Update the file AndroidManifest.xml

<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="15" />

        android:theme="@style/AppTheme" >
            android:label="@string/title_activity_main" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

            android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" >
                <action android:name="in.wptrafficanalyzer.servicealarmdemo.demoactivity" />
                <category android:name="android.intent.category.DEFAULT" />

12. Screenshots of the application

Setting an Alarm

Figure 5 : Setting an Alarm


Opening the AlertDialog window when the alarm goes off

Figure 6 : Opening the AlertDialog window when the alarm goes off

13. Download the source code of this alarm application

14. Reference

How to hire me?

I am George Mathew, working as software architect and Android app developer at

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , , , , , ,

20 Responses to Setting up alarm using AlarmManager and waking up screen and unlocking keypad on alarm goes off in Android

  1. Syamantak Basu on September 3, 2012 at 7:13 pm

    A really helpfull website. Lots of daily use application examples as well as uncommon examples. Really helpfull.

  2. zen kun on January 24, 2013 at 10:18 pm

    WOW excelente :) me funciono super, hice unas modificaciones como agregar sonido y vibración :) realmente genial!!! gracias

  3. zen kun on January 24, 2013 at 10:20 pm

    Ups in english, really works :) i add sound and vibration :) and wow amazing work :) i was fighting with keyguard and using wakelocks :S and i did use the flags in window manager but seem i was doing wrong :) very helpfull :)

    • Sungmok Jung on April 4, 2013 at 7:16 pm

      how did you add sound and vibration function on this source?
      can you let me know how it could be done? thanks, Jung :)

  4. alan on March 31, 2013 at 6:41 pm

    a very great source code, but does it work in eclipse emulator?

  5. Ribin Haridas on April 26, 2013 at 3:02 pm

    nice example loving it. very usefull. Thank You

  6. bartosg86 on June 16, 2013 at 3:35 pm

    Great work, thank you. Do you have any idea why waking up screean and unlocking keypad works on emulator, but doesn’t on phone? (sony ericsson live with walkman)

  7. Amrit on October 11, 2013 at 6:49 pm

    Its crashing on Samasung galaxy S3 after setting alarm…. :( :( :(

  8. diamond on March 11, 2014 at 6:47 pm

    How it link from one class to another class?

  9. Nitram on September 4, 2014 at 5:28 pm

    Hi there …

    thanks for this contribution …

    Currently I’m programming an alarm application to customize to my needs. After your example, I have been easier, but what I need now is to make the application work when the phone is off, not on standby, so that the alarm when you have to ring first turn on the phone and then ring.

    Is this possible ??

    Thanks and regards.

  10. Nitram on September 16, 2014 at 3:01 pm

    Good Morning:

    very good explanations … just a question … if the phone is OFF (not in standby, but completely off), ¿I can turn it on from the application I programmed, and the alarm sounds, without any intervention by the user? (In the same way as the default one alarm on the phone).

    Thanks … greetings

  11. Mina Dahesh on September 17, 2014 at 6:16 pm

    if i want to use notification instead of alert dialog, what should i do?

  12. Z.aH on September 21, 2014 at 1:37 pm

    does this alarm work after device reboot??

  13. ayon on December 10, 2014 at 10:03 am

    is it possible to set more than one alarm at the same time?

  14. Diana on December 15, 2014 at 3:22 am

    Hello, I have a problem when I did this, instead of showing the Alarm Dialog Box when its time, it only shows the error message saying unfortunately this app need to be stopped and it exits the app straight away. may I know why is the Alarm Dialog Box is not showing? THANKS!

  15. Madhu on October 5, 2015 at 4:08 pm

    Hi ….Nice’s working…..I am trying to set Alarm in Frame of navigationdrawer.. but Dialogfragment is not displayed…can i send my code to your mail_id?

  16. Z.AH on November 5, 2015 at 3:34 pm

    Hi Ayon, it depends on Android version such that in version 5: its allowed toset more than one alarm at the same time but only one of them will shows up
    In version 4.4 it’s also allowed and all the alarms will be played such that if you set a ringtone for the alarm with 3 simultaneously your ringtone will be played 3 time as well

  17. Z.AH on November 5, 2015 at 3:37 pm

    Hello Daina, most likely your problem is in the creation/initialization of the dialog box.

  18. Z.AH on November 5, 2015 at 3:40 pm

    For future reads I will answer my own question;
    The alarms does not work after device reboot. So if you want to do so you should reset them on device reboot which is easy task to accomplish.

  19. Sourav on March 18, 2016 at 1:33 pm

    Hello Sir,nice tutorial..its i want to set snooze and skip option ..can you give some idea or codes for that..? thank you

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner