1

In my app I would like that a certain method of mine (call it toSched) will run at a given time in the future (I'm using Timestamp for knowing when).

How can this be done, and is it possible to do it even if the phone is turned off (assume there is enough battery) ?

*I know I should use AlarmManager but I'm not sure how

Belgi
  • 14,542
  • 22
  • 58
  • 68
  • possible duplicate of [How to set a timer in android](http://stackoverflow.com/questions/1877417/how-to-set-a-timer-in-android) – paulsm4 Oct 15 '11 at 04:12

2 Answers2

2

You want to use the Android Alarm Manager. You do it by creating a PendingIntent (which is what you want to run) and then calling the set method. Checkout this stackoverflow post for more info.

What most people do is create a PendingIntent that is a broadcast. Then they create a broadcast receiver to receive that broadcast and do what ever is supposed to be done. Here's an example of "calling a method" to start an activity. But you can just put your own arbitrary code in the receiver to do what ever random task.

Community
  • 1
  • 1
Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • I read some posts and tried to understand exactly what to do, but I don't understand... Can you please add a code example ? (I looked at some code examples but none tried to scheduale a method) – Belgi Oct 15 '11 at 04:35
  • I edited my answer and added a little bit about how most people use the alarm manager to do a particular task sometime in the future. – Kurtis Nusbaum Oct 15 '11 at 04:39
  • I tried using the code in the example but I'm getting an error on "Intent intent = new Intent(ctx, AlarmReceiver.class);" what is ctx ? edit : there is also a problem with the first parameter of the next line – Belgi Oct 15 '11 at 05:02
  • I'm guess ctx just means context. You have to give the Intent a context in which to run. – Kurtis Nusbaum Oct 15 '11 at 05:05
  • I'm not sure what is the meaning of the context in which it runs...what should I give as the first parameter ? – Belgi Oct 15 '11 at 05:10
  • Please look at the Intent API http://developer.android.com/reference/android/content/Intent.html – Kurtis Nusbaum Oct 15 '11 at 05:12
1

There's several ways of looking at this. One alternative (the one I think you're looking for) is discussed in this Stack Overflow thread:

Another is to make sure your program gets invoked when you need it to:

Community
  • 1
  • 1
paulsm4
  • 114,292
  • 17
  • 138
  • 190