20

I am a bit confused about Timer and AlarmManager used in Android.

What are the main differences between them?

They are both scheduling a task to run at every A seconds. And what is the main scenario that they are preferred to be used?

For example, for X situation, use Timer but on the other hand, for Y situation, use AlarmManager.

jellyfication
  • 1,595
  • 1
  • 16
  • 37
mavzey
  • 379
  • 1
  • 5
  • 13

2 Answers2

32

A Timer will start a thread that will keep track of when to start your code. If the device goes asleep, so will the timer thread and your code won't be executed on time. AlarmManager's alarms, on the other hand, are kernel-level. Depending on how you register them, you can request to wake up the device, or execute the next time something wakes up the device. Alarm's are generally preferable and use less resources.

Nikolay Elenkov
  • 52,576
  • 10
  • 84
  • 84
  • 2
    Adding to this answer, documentation says that `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.` – Pankaj Kumar Jan 29 '13 at 09:25
  • 1
    Correct, but that doesn't mean that it is OK to do lengthy operations in `onReceive()`. If you need to do anything that could potentially take some time (disk or network access) you should start a service to do the work (which in turn will have to use wake locks as necessary) and return from `onReceive()` as quickly as possible. – Nikolay Elenkov Jan 29 '13 at 12:26
  • Yes you are right. And if I am not wrong he can use IntentService (as we can start a service from alarmmanager), right? – Pankaj Kumar Jan 29 '13 at 12:33
0

Timer starts a service it executes code very frequently even thought it wasn't actually doing anything.

Alarmmanager on the other hand will start a Service that runs in the background always, this is what you want to use to schedule your code to run when your app isn't open.

TheWhiteRabbit
  • 15,480
  • 4
  • 33
  • 57