Wednesday, October 13, 2010

A simple example of Alarm Service, using AlarmManager

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.

In this exercise, a scheduled alarm of 10 seconds will start a service, MyAlarmService.








Modify main.xml to have two button to start and cancel the alarm.
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

<Button

android:id="@+id/startalarm"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Start"

/>

<Button

android:id="@+id/cancelalarm"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Cancel"

/>

</LinearLayout>


AndroidAlarmService.java, the main activity.
package com.exercise.AndroidAlarmService;



import java.util.Calendar;



import android.app.Activity;

import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.os.SystemClock;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



public class AndroidAlarmService extends Activity {



private PendingIntent pendingIntent;





/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Button buttonStart = (Button)findViewById(R.id.startalarm);

    Button buttonCancel = (Button)findViewById(R.id.cancelalarm);



    buttonStart.setOnClickListener(new Button.OnClickListener(){



 @Override

 public void onClick(View arg0) {

  // TODO Auto-generated method stub



  Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);

  pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);



           AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);



           Calendar calendar = Calendar.getInstance();

           calendar.setTimeInMillis(System.currentTimeMillis());

           calendar.add(Calendar.SECOND, 10);

           alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

       

  Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();

 }});



    buttonCancel.setOnClickListener(new Button.OnClickListener(){



 @Override

 public void onClick(View arg0) {

  // TODO Auto-generated method stub

  AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

  alarmManager.cancel(pendingIntent);



           // Tell the user about what we did.

           Toast.makeText(AndroidAlarmService.this, "Cancel!", Toast.LENGTH_LONG).show();





 }});



}

}


MyAlarmService.java, it will be started in 10 seconds triggered by AlarmManager
package com.exercise.AndroidAlarmService;



import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;



public class MyAlarmService extends Service {



@Override

public void onCreate() {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();

}



@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();

return null;

}



@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();

}



@Override

public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

super.onStart(intent, startId);

Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();

}



@Override

public boolean onUnbind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();

return super.onUnbind(intent);

}



}


Finally, modify AndroidManifest.xml to have our MyAlarmService listed as service.
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

  package="com.exercise.AndroidAlarmService"

  android:versionCode="1"

  android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">

    <activity android:name=".AndroidAlarmService"

              android:label="@string/app_name">

        <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>

    </activity>

<service android:name=".MyAlarmService" />

</application>

<uses-sdk android:minSdkVersion="4" />



</manifest>


download filesDownload the files.


Related articles:

- Schedule a repeating alarm

- App Widget using Alarm Manager

- Send SMS in Alarm Service at a pre-defined time

- Using AlarmManager to start a Scheduled Activity


63 comments:

  1. Thank you very much!

    I'm starting programming on Android and i need some help with the AlarmManager.

    ReplyDelete
  2. Hi All,
    I want to know, if i set an alarm at some time "X"....and if my device is pwoered off during that time, then will alarm still ring?
    Currently on 2.2 phone does not turns on.
    If i want to support this feature then how to do it?

    ReplyDelete
  3. hello Vithal,

    in the function call alarmManager.set(), what you set in the first parameter? RTC/RTC_WAKEUP?

    RTC_WAKEUP should wake up the device when it goes off.

    ReplyDelete
  4. thanks...
    I wanna ask that if i want to automatically send sms at particular time then how to integrate this function with sms?

    ReplyDelete
  5. hello Sergio,

    I think you can simple call a method to send SMS using SmsManager, with pre-defined number and text without UI activity.

    For your reference:
    Send SMS using android.telephony.SmsManager

    ReplyDelete
  6. Hello Android Er
    I think u din get my problem. I want to develop an application where in i want to send sms at pre defined time. My problem is that how to integrate Alarmmanager() to sendsms()
    so that in the same UI, user should have option to write sms n set time too. And at that set time the sms should be sent.

    ReplyDelete
  7. Hi,

    i am faceing problem in setting alarm for a perticular date and time for eg: i need to set at alarm on 2/4/2011 8AM i tried to do it by modifying the exaple give by you but its not working. and in the example code when i set the delay of 60 seconds instead of 10 seconds its not working the alarm services is called just after we press "start"

    for setting alrm for perticular date i gone through differnt eg on net but nothing worked could you please help me on this

    ReplyDelete
  8. hello Niju,

    Would you send me your code?
    er.android@gmail.com

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. Can you use the AlarmManger to run at repeated intervals? How does it compare with using a Service regarding battery life of your device?

    ReplyDelete
  11. Hello Account,

    for running at repeated intervals, pls. refer Schedule a repeating alarm.

    For battery life, I THINK - the main issue is how frequently you set the alarm repeat.

    ReplyDelete
  12. I keep getting errors at these two points AlarmManager.RTC_WAKEUP and alarmManager.cancel(pendingIntent);

    it doesn't recognize RTC_WAKEUP and asks to create the variable same as cancel it asks to create the method

    ReplyDelete
  13. Hello Account,

    You can try to download the project here.

    In Eclipse, New a Android Project, check to select "Create project from existing source", browse to the download and unzipped folder.

    ReplyDelete
  14. Thanks, the app is working fine now but I have a few questions

    1. In setting the repeating duration, is there another way to represent time in hours in other than in milliseconds?

    2. When the AlarmManager fires the service and the service completes its task, does the service keep running or does the AlarmManger stop the service?



    3. With regards to my App, I'm trying to get my UI updated automatically at hourly intervals.

    I need the service start, update the UI then be destroyed at every interval.

    ReplyDelete
  15. Another question is it possible for me to get the AlarmManger to run a method instead of fire an intent?

    ReplyDelete
  16. Hello Account,

    - I have no idea to set repeating duration in hour. But, it's easy to convert from hour to millisecond.

    - In this exercise, the service keep running.

    - Please refer Using AlarmManager to start a Scheduled Activity

    ReplyDelete
  17. Thx for this exemple, but i have a question.

    When I schedule an alarm an the user do a "force stop", my alarm doesn't ring ... I'm okay with that ... but how can I detect that the alarm will no ring ?

    I try a getBroadcast with FLAG_NO_CREATE but it find something ... and it doesn't ring ... don't understand why ... if you can help me ... thanks a lot.

    ReplyDelete
  18. how should I set the alarm for user given date and time in place of 10 milliseconds in the above code

    ReplyDelete
  19. hi, i want to make repeatabel alarm, for example, i want to set an alarm everyday on 3 o'clock for a week, and the alarm will ring everyday at 3 o'clock for a week, how i can do that? thaks before

    ReplyDelete
  20. hello nishant,

    I haven't tried it. But I think Android cannot have too accurate timer in this way.

    ReplyDelete
  21. hello nishant,

    Please check Use Handler and Runnable to generate a periodic event.

    You can set the postDelayed() 0f 10(ms), but don't know if it's too accuracy or not!

    ReplyDelete
  22. Thanks a lot for your great tutorial, and the quality. I ve spend more than a week on your blog.
    If you can give us an ex how to manage with global variable with this code (alarm mananger) will be great.
    Thanks again !

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Hi Android Er! You have a great blog here, many thanks for your tutorials, they've been a great help!

    Regarding this Alarm Service example, it's all working fine but I can't see the functions onBind(), onDestroy() and onUnibind() being executed! Am I not using the app as it should or is it supposed to do so?

    Regards and keep up the good work!

    ReplyDelete
  25. I was wondering if you could re-upload your project file.

    Thanks

    ReplyDelete
  26. Hi, i have a service which is started after receiving a particular intent through Broadcast receiver. Now, since there is no activity involved in this, the service could be shut down by Android if there is no enough resources available. I don't want this to happen. Can i use AlarmManager to activate my service for every 5 min or less?

    ReplyDelete
  27. Thanks alot.
    But i didn't see where alarm is set.

    ReplyDelete
  28. Hello
    Alarm set in the code alarmManager.set(...)

    ReplyDelete
  29. Hai Android Er,
    i want to know, through one activity we will call another activity from that activity to another ,if in the middile activity there is a need of performing any calucalation of two numbers and need of pressing abutton to calucalate at that time how we can acheive this

    ReplyDelete
  30. i am trying to follow this code to create the alarm manager app. i am having issues creating the myalarmmanager.java file. how do i create it ?
    thanks,

    ReplyDelete
  31. hello KN,

    Can't you see the Toast of "MyAlarmService.onStart()"?

    The Cancel button cancel the alarm the alarm.

    Can you download the project and try to create project from existing source?

    ReplyDelete
  32. This just crashes. The application starts on the emalulator, and a few seconds later "the application has stopped unexpectedly". No errors in Eclipse.

    ReplyDelete
  33. thanks for the example !
    how to do something every sunday at 08:00 ?

    thanks

    ReplyDelete
  34. This is good example but how to set alarm with for more than one event any example please post the same.

    Thanks

    ReplyDelete
  35. The phone shows start but no alarm were activated. can you help thx

    ReplyDelete
  36. Is it because of the android version i am using? Currently using 2.33

    ReplyDelete
  37. You'll have to be more specific. Have you tried putting in breaks or toasts (f.ex.) in your code, to see where it stops?

    It's not because of your Android version.

    ReplyDelete
  38. the phone alarm was not activated

    ReplyDelete
  39. Ok, I'm not going to try helping people who don't bother providing any info with their questions. I asked you to be more specific, and you just repeat the same uninformative sentence. I ask you if you've tried ANYTHING to figure out the problem for yourself, and you ignore it. "This isn't working, please help" is NOT an intelligent question, and trying to help is a waste of time.

    ReplyDelete
  40. I am running the application on my samsung galaxy tab it works perfectly except for the part where i press the start button.No alarm were activated.
    I even tried toast already, so please see if you can help. Thanks.

    ReplyDelete
  41. It's another exercise: Create alarm set on a specified time, using AlarmManager.. ~ Tested on Galaxy Nexus(4.0.2) and HTC Flyer(3.2.1).

    ReplyDelete
  42. Android Er do you know why the phone isn't activated?? The toast text came out but not alarm.

    ReplyDelete
  43. Hi,

    How can we schedule task for particular day. Let say I would like to schedule some task on Monday @ 8AM & 9PM AND some task on tuesday @ 10AM & 7PM. How can we achieve this kind of functionality. Please kindly help me.

    ReplyDelete
  44. hai.. my problem same with thomas, the toast text came out but not alarm. Can I know what problem?

    ReplyDelete
  45. Awesome Man, i was searching this for days, thanks

    ReplyDelete
  46. cool sample
    how to change this sample that Every 10 minutes a message appears

    ReplyDelete
  47. Thanks for posting this.

    ReplyDelete
  48. Hello ER.
    I want to do a long running task in the background thought of using Intentservice,this background work updates the activity class repeatdly with a interval of 30 seconds so thought of using Alarmmanager.
    Now please suggest me the options for doing same.

    ReplyDelete
  49. hello ER,
    Can you suggest me how to update alarm time in between or can you suggest me other solution. My problem is like I m receiving data every 1sec via bluetooth , and if data doesn't come for 5 sec , i have to indicate in text.

    ReplyDelete
  50. hello Paritosh Bairagi,

    I think you can cancel the on-going alarm and restart another alarm when bluetooth received.

    ReplyDelete
  51. Hi Thanks a lot.
    Tutorial of your alarm manger is easy to understand and its very helpful. I need to play a mp3 song in alarm service, how to play?

    ReplyDelete
  52. Hi All Dear friend,

    i create an app. in this app i want to that if i set an alarm at some time "X"....than my device automatically switch off on that time....
    so pls help me ...

    ReplyDelete
  53. Man U R Awesome

    you helped me allot with this i will integrate this in unity 3d

    ReplyDelete
  54. i don't get any sound.why is that?

    ReplyDelete
  55. how to remove particular timed alarm?

    ReplyDelete
  56. Hey, can u tell me how to use sensor in this app to stop alarm by shaking the phone??

    ReplyDelete
  57. me ayudarias a programar la alarma cada dos horas del dia porfavor

    ReplyDelete
  58. i want to send location to sever in background plzz provide me code i have function to get location and sending to server but i want to send in background plzz provide me code

    ReplyDelete