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:

Sergio said...

Thank you very much!

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

Vithal said...

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?

Erik said...

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.

suvirai said...

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

Erik said...

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

suvirai said...

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.

Erik said...

hello sujata,

Is it what you want?
Send SMS in Alarm Service at a pre-defined time

Niju said...

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

Erik said...

hello Niju,

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

Kaushal Butala said...
This comment has been removed by the author.
Account said...

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

Erik said...

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.

Account said...

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

Erik said...

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.

Account said...

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.

Account said...

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

Erik said...

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

Oriane & Fabien said...

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.

nishant said...

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

Handy Lukito said...

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

Erik said...

hello Handy,

please refer Schedule a repeating alarm

Erik said...

hello nishant,

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

Erik said...

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!

PeuchereBike said...

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 !

Unknown said...

thanks man helped a lot!

androjes said...

Thank you!
I'll start from here:)

androjes said...
This comment has been removed by the author.
masterT said...

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!

Unknown said...

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

Thanks

priya said...

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?

Akashissky said...

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

Erik said...

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

reddy said...

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

Aadi said...

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,

Erik said...

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?

Den Fyren said...

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

Eitan said...

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

thanks

Srinivasa said...

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

Thanks

Rong Hwee said...

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

Rong Hwee said...

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

Den Fyren said...

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.

Rong Hwee said...

the phone alarm was not activated

Den Fyren said...

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.

Rong Hwee said...

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.

Erik said...

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).

Rong Hwee said...

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

Rong Hwee said...

Phone Alarm**

Keyur said...

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.

foong said...

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

Darshan said...

Awesome Man, i was searching this for days, thanks

Eitan said...

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

Anonymous said...

Thanks for posting this.

Unknown said...

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.

Unknown said...

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.

Erik said...

hello Paritosh Bairagi,

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

Unknown said...

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?

Unknown said...

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 ...

Anonymous said...

Man U R Awesome

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

Anonymous said...

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

Add Surf Earn said...

how to remove particular timed alarm?

Unknown said...

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

Unknown said...

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

Unknown said...

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