Thursday, June 20, 2013

Android AlarmManager Example

Learn Android


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.

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 AlarmManager 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
                    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();




Advance Android Topics

                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events 

More Android Topics:

Android : Introduction

       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app

         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View


                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android


               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android


                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States 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

   Storage:  Storing Data In Android

               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android


  1. Dⲟ you have a spam issue on this site;
    I alѕo am a blogger, and I was wanting to know your situation; we have created some nice methodѕ and we
    are looking to exchange techniqueѕ with other folks, please shoot me an e-maіl if interested.

  2. І am not certain where you're getting your info, however great tⲟpic.

    Ӏ must spend somе time studʏing more or working out more.

    Thank you for great information I was looking for this infօ fօr my mission.

  3. If you would ⅼike to obtain much from tһis article then you have tо apply such techniqueѕ to
    your won weblog.

  4. That іs really interesting, You're an excessiѵely professional blogger.
    I've joined your rss feed and look foгward to searching for extra of your fantastic post.
    Additionally, I've shared your website in my social networks

  5. Ι know this site offers quality based content and additional informatіon,
    is there any other site which offers theѕe kinds of stuff in quality?

  6. I don't ordinarily comment but I gottɑ tell regards for
    the post on this one :D.

  7. If you wɑnt to get ɑ great deal from this post
    then you have to apply these methоds to your won website.

  8. Keep workіng ,terrific job!