Saturday, June 1, 2013

Scheduling Task Using Alarm Manager


Many a times we want some task to be performed at some later time in future.
For Example: In SMS Scheduler we want a SMS to be send at some later time, or Task Reminder in which we want to be reminded  about a task at a particular time, to implement all these things we use AlramManager class.

AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted. 

                 The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes. If your alarm receiver called Context.startService(), it is possible that the phone will sleep before the requested service is launched. To prevent this, your BroadcastReceiver and Service will need to implement a separate wake lock policy to ensure that the phone continues running until the service becomes available.

AlarmManager Example

In the example I will schedule an alarm to send SMS at a particular time in future.
We have two classes
1: MainAcitvity: in this class, we will schedule the alarm to be triggered at particular time .
2: AlarmReciever: when the alarm triggers at scheduled time , this class will receive the alarm, and send the SMS.

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone

Permission Required
we need <uses-permission android:name=""/>  permission to use the AlarmManger in our application, so do not forget to declare the permission in manifest file

AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >

            <uses-sdk android:minSdkVersion="8"
                             android:targetSdkVersion="17" />
             <!-- permission required to use Alarm Manager -->
            <uses-permission android:name=""/>
            <!-- permission required to Send SMS -->
            <uses-permission android:name="android.permission.SEND_SMS"/>
                     android:label="Demo App" >
                               android:label="Demo App" >
                                           <action android:name="android.intent.action.MAIN" />

                                           <category android:name="android.intent.category.LAUNCHER" />
               <!-- Register the Alarm Receiver -->
                   <receiver android:name=".AlarmReciever"/>



        android:text="Alarm Manager Example"
        android:textAppearance="?android:attr/textAppearanceLarge" />

        android:text="Schedule The Alarm"


public class MainActivity extends Activity

       public void onCreate(Bundle savedInstanceState)


    public void scheduleAlarm(View V)
            // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time, 

            // we fetch  the current time in milliseconds and added 1 day time
            // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day       
            Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

            // create an Intent and set the class which will execute when Alarm triggers, here we have

            // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
            // alarm triggers and 
            //we will write the code to send SMS inside onRecieve() method pf Alarmreciever class
            Intent intentAlarm = new Intent(this, AlarmReciever.class);
            // create the object
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

            //set the alarm for particular time
            alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
            Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();


public class AlarmReciever extends BroadcastReceiver
            public void onReceive(Context context, Intent intent)
                    // TODO Auto-generated method stub

                      // here you can start an activity or service depending on your need
                     // for ex you can start an activity to vibrate phone or to ring the phone   
                    String phoneNumberReciver="9718202185";// phone number to which SMS to be send
                    String message="Hi I will be there later, See You soon";// message to send

                    SmsManager sms = SmsManager.getDefault();
                    sms.sendTextMessage(phoneNumberReciver, null, message, null, null);

                    // Show the toast  like in above screen shot
                    Toast.makeText(context, "Alarm Triggered and SMS Sent", Toast.LENGTH_LONG).show();



New Advance Topics:                   Android LiveWallpaer Tutorial
Android ImageSwitcher                    Android TextSwitcher                                Android ViewFlipper
Android Gesture Detector               Handling/Detecting Swap Events                Gradient Drawable
Detecting Missed Calls                    Hide Title Bar                                           GridView Animation
Android AlarmManager                 Android BootReceiver                       Vibrate Phone In a Desirable Pattern    
Developing for Different Screen Sizes           Showing Toast for Longer Time       Publishing your App
How to publish Android App on Google Play

 Beginning With Android
      Android : Introduction(What is Android)                                                              Configuring Eclipse for Android Development
     Creating Your First Android Project                                           Understanding Android Manifest File of your android app

 Advance Android Topics                                                              Customizing Android Views

Working With Layouts                                                                Working With Views

Understanding Layouts in Android                                                   Using Buttons and EditText in Android
Working with Linear Layout (With Example)                                     Using CheckBoxes in Android
Nested Linear Layout (With Example)                                              Using AutoCompleteTextView in Android                                                                                          Grid View
Relative Layout In Android                                                               ListView
Table Layout                                                                                   Android ProgressBar
Frame Layout(With Example)                                                          Customizing ProgressBar
Absolute Layout                                                                             Customizing Radio Buttons
Grid Layout                                                                                    Customizing Checkboxes In Android

Android Components                                                                 Dialogs In Android

Activity In Android                                                                    Working With Alert Dialog
Activity Life Cycle                                                                    Adding Radio Buttons In Dialog
Starting Activity For Result                                                       Adding Check Boxes In Dialog
Sending Data from One Activity to Other in Android                    Creating Customized Dialogs in Android
Returning Result from Activity                                                   Creating Dialog To Collect User Input
Android : Service                                                                     DatePicker and TimePickerDialog
BroadcastReceiver                                                                   Using TimePickerDialog and DatePickerDialog In android

Menus In Android                                                                ListView:
Creating Option Menu                                                               Populating ListView With DataBase
Creating Context Menu In Android                                              Populating ListView with ArrayList
                                                                                               ListView with Custom Adapter

Toast                                                                                      Working With SMS
Customizing Toast In Android                                                       How to Send SMS in Android
Customizing the Display Time of Toast                                        How To Receive SMS
Customizing Toast At Runtime                                                  Accessing Inbox In Android
Adding Image in Toast
Showing Toast for Longer Time

TelephonyManager                                                            Storage: Storing Data In Android
Using Telephony Manager In Android                                          SharedPreferences In Android
                                                                                              Reading and Writing files to Internal Stoarage
Working With Incoming Calls                                             DataBase
How To Handle Incoming Calls in Android                                Working With Database in Android
How to Forward an Incoming Call In Android                            Creating Table In Android
CALL States In Android                                                          Inserting, Deleting and Updating Records In Table in Android

Notifications In Android
How To Vibrate The Android Phone
Sending Email In Android
Opening a webpage In Browser
How to Access PhoneBook In Android
Prompt User Input with an AlertDialog


  1. Hi kamlesh..
    what should we use if we want to schedule the alarm at specific date and time..for eg. alarm trigger on 10th july 2013, 12:00:00

    1. Hi Rekha
      With following code you will get the current time in Milseconds.
      Long time = new GregorianCalendar().getTimeInMillis();
      You can some value like 24*60*60*1000 to schedule the alarm for tommorow.

      1: The other way is Use time picker and date picker and schedule the alarm at User Selected date or Time.

      2: GregorianCalendar gc=new GregorianCalendar(year, month, day, hour, minute, second); you can pass the arguments here.
      Like schedule at 10th july 2013, 12:00:00
      GregorianCalendar gc=new GregorianCalendar(2013, 6, 10, 12, 00, 00);

      You can also set the time as
      gc.set(Calendar.DAY_OF_MONTH, 10);
      gc.set(Calendar.YEAR, 2013); and so on

      Let me know any more concern.

    2. @Kamlesh: Dear Admin, I tried GregorianCalendar gc=new GregorianCalendar(year, month, day, hour, minute, second);

      Then the error comes at AlarmManger.set(), it says to change thr type of gc to Long. (i.e. gc cannot be GregorianCalendar).

      So if i do change the above mentioned thing, then gc cannot be Long.

      I cant even try casting here....

      So pls give a solution .....
      Thanks in Advance.

    3. Admin I removed all the errors, I was missing getTimeInMillis().

      Bt the code is still not getting invoked @ 12:00:00.....pls guide.

      Or atleast tell where can i paste my code, such that u can give a chk.

  2. i am new to Android and working on a app which take a int value from "if statements".Now the 1st prob is m not getting how to send value to broadcastReceiver and second is int value changes on "if " condition, now how can i send the value that is stored according to the condition

  3. Nice tutorial dude.... It helps me lot..

  4. Hi Admin....Nice Tutorial. Thanks.

    But i have a doubt. Your code work awesome once.

    What if i want to do it again & again.

    I mean u did it for 1 day. What if i want to do it EveryDay that too Dynamically....

    Please Reply.....Thanks in Advance.

  5. Dear Admin, Nice Tutorial.

    But could u pls guide me that how to execute this code everyDay.....pls.

    i.e. a msg shud go everyday. Dynamically.

    I need this code. Thanks in advance.

  6. You are a LIFE-SAVER!

    Oh man been looking around for an example on how to trigger an event in future and all examples I came across are so unnecessarily complicated and convoluted!

    Your code rocks! I love it!
    Thanks a lot for sharing this!

  7. Thank you very much. We were trying to make a similar app, but were not able to schedule the events. Now , thanks to you, we know :) Thanks again...

  8. Wah!!! Thank you so much for this... This is the best and most simplest example of AlarmManager I could find on the net....

  9. I tried following your tutorial, however it refuses to work unless I make the AlarmReciever class static, which leads to a bunch of other problems for me :). How did you manage to avoid that? Thanks!!!

  10. I tried following your tutorial, however it refuses to work unless I make the AlarmReciever class static, which leads to a bunch of other problems for me :). How did you manage to avoid that? Thanks!!!

  11. Nice one, but what happens, if the app stop working on the background?

  12. Never mind it works like a charm!!! Love you!

  13. What if i want to run my code multiple time without any pattern,like 9am,10pm then again tomorrow at same time how to do that with one AlarmManager object?

  14. To make this Alarm *REPEAT* at the time intervals you want, you just need to change some code in *MainActivity.Java*
    Here we go ...

    (1) Look for this line in the **

    Long time = new GregorianCalendar().getTimeInMillis() + 24*60*60*1000;

    (Hey be careful, this 24*60*60*1000 in the above line is for *ONE DAY TIME* this alarm will set off after you've clicked the button in the app.
    So let's change it into shorter time span for testing in the first place.
    How about we set it into about 15 seconds?

    OK, 15 seconds in *Milliseconds" is 15000. (Just multiply it by 1000 )

    So re-write the above code with like this. (And delete the old line of code after this)
    We get new one.

    Long time = new GregorianCalendar().getTimeInMillis() + 15000; // Remember 15 seconds (for testing)

    (2) Add this line below it.

    int time2 = 20000; // That is 20 seconds * 1000

    OK, we now got two *time* varibles!
    The first original "time" is the time when our alarn will set off (after button click of course!)
    The newly-added "time2" is the time interval that our alarm will take to repeat itself AGAIN! (after 20 seconds in our case)

    (3) Finally change the whole line before the last line into this one.

    alarmManager.setRepeating((AlarmManager.RTC_WAKEUP),time, time2,PendingIntent.getBroadcast(this,1,intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));

    Here we just made two changes in the codes above!
    The first one is: We changed "set ..." into "setRepeating((...."
    And the second one is: We just added our new variable "time2" after the original "time" varible.

    That is it. Rebuild the app with these changes and then you get an alarm REPEATING EVERY "time2" time!! :)

    For further clarity, here below is the snippets of code with the changes we just made:


    Long time = new GregorianCalendar().getTimeInMillis() + 15000; // Alarm will set off after 15 seconds
    int time2 = 20 * 1000; // Repeat for *EVERY* 20 second

    // create an Intent and set the class which will execute when Alarm triggers, here we have
    // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
    // alarm triggers and 
    //we will write the code to send SMS inside onRecieve() method pf Alarmreciever class

    Intent intentAlarm = new Intent(this, AlarmReciever.class);

    // create the object

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //set the alarm for particular time

    alarmManager.setRepeating((AlarmManager.RTC_WAKEUP),time, time2,PendingIntent.getBroadcast(this,1,intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();


    By the way, you can comment out the code that actually sends SMS in the ** file if you don't want SMS being sent during testing.
    I hope this helps. Good luck! :)

  15. Hi, how can a I link my user preferred date and time using date and time picker to the alarm system.