Friday, May 31, 2013

Android Alarm Manager

AlarmManager

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.


Android 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="com.android.alarm.permission.SET_ALARM"/>  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="http://schemas.android.com/apk/res/android"
    package="com.learnandroideasily.blogspot"
    android:versionCode="1"
    android:versionName="1.0" >

            <uses-sdk android:minSdkVersion="8"
                             android:targetSdkVersion="17" />
             <!-- permission required to use Alarm Manager -->
            <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
            <!-- permission required to Send SMS -->
            <uses-permission android:name="android.permission.SEND_SMS"/>
   
            <application
                     android:icon="@drawable/ic_launcher"
                     android:label="Demo App" >
                    <activity
                               android:name=".MainActivity"
                               android:label="Demo App" >
                              <intent-filter>
                                           <action android:name="android.intent.action.MAIN" />

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





main.xml





<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center_vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:gravity="center_horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Alarm Manager Example"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        android:layout_marginTop="25dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Schedule The Alarm"
        android:onClick="scheduleAlarm"/>

</LinearLayout>



MainActivity.java






public class MainActivity extends Activity
{

       @Override
       public void onCreate(Bundle savedInstanceState)
      {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);

      }

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

}

AlarmReciever.java







public class AlarmReciever extends BroadcastReceiver
{
         @Override
            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


Miscellaneous
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



23 comments:

  1. Example not working for me..

    ReplyDelete
    Replies
    1. What is the problem ? Just let me know, Will surely help you.

      Delete
  2. its not going to broadcast receiver.for me

    ReplyDelete
    Replies
    1. Hi Jayshree
      Please elaborate your problem so that I can understand and provide you support.

      Delete
    2. That's simple. Because it's "receiver" not "reciever"

      Delete
  3. Thanks from Spain has been the definitive tutorial to understand properly

    ReplyDelete
  4. Thank you for your post! :)

    ReplyDelete
  5. Hi Kamalesh,
    In this example you though us how to set alarm and send SMS. My question is it possible to decode the received SMS and set our alarm based on the time specified in that SMS. Thanks in advance.

    ReplyDelete
    Replies
    1. Hi Prabhu
      Yes it is possible to set an alarm with thementioned in SMS.
      For decoding the SMS and fetching SMS body pls follow my post http://www.learn-android-easily.com/2012/11/how-to-receive-sms.html

      fetch the SMS body and set your alarm at particular time.
      Pls feel free for more help if required.

      Delete
  6. Hi Kamalesh,
    Thanks for the tutorial . Is it possible to decode the received SMS and Set our alarm based on the time specified in the SMS

    ReplyDelete
  7. Hi kamalesh ,
    thank you and could you just tell me how to check this code in emulator ..ya i googled before posting this question.

    ReplyDelete
    Replies
    1. Yes you can check in emulator.
      Just start the emulator, open "Emulator Control" and sent a SMS to emulator from Emulator Control.

      To open Emulator Control click on "Window" menu then clcik "Show View" and select Emulator Control.

      Delete
  8. Hi Kamlesh,

    I tried this on my mobile (and also reduced the time from 24hrs to one min). But nothing happens.I mean the is no sms sent. Please help.

    Saugat

    ReplyDelete
  9. Hi Kamlesh,

    I tried this application on my actual device, but it doesn't seem to work. I have changed the "time" to 30 secs (Long time = new GregorianCalendar().getTimeInMillis()+(30*1000); ) but after waiting for 30 seconds, nothing happens. I mean there is no message sent.

    Please help.

    Saugat

    ReplyDelete
  10. As soon as I save the alarm set my onreceive intent is called which displays the message "Alarm triggered....." and it does not trigger when the actual time comes. What might be wrong

    ReplyDelete
  11. If anyone is wondering why this isnt working, its because AlarmReceiver is spelled wrong at the end of the manifest file where he registers the receiver under the name "AlarmRecIever" for android:name (as previously stated by another anonymous). It really should be edited to the fixed spelling, that one litte thing caused me lots of trouble.

    ReplyDelete
    Replies
    1. There is no spelling mistake. AlarmReceiver is written correctly at all the places.

      Delete
  12. very good post, it was really informative thanks a lot for posting…
    Mobile App Development

    ReplyDelete
  13. I tried to implement the code but when the apps was running "Unfortunately, Demo App has stopped" appeared

    ReplyDelete
  14. I implemented the codes but when the app was running, "Unfortunately, Demo app has stopped" is appeared.

    ReplyDelete
  15. works right here !

    you guys are great !

    Thanks

    ReplyDelete