Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimerTask vs AlaramManager, Which one should I use?

Tags:

android

I am working on an application which triggers an action (say toast message) every 10 minutes after the screen is ON and stops the action after the screen is OFF. I have used TimerTask for this purpose. Shall I start using AlaramManager instead of TimerTask or shall I keep using TimerTask ? I know the difference between the two but can't figure out which to use.

like image 786
Miss Noob Avatar asked Dec 07 '22 02:12

Miss Noob


2 Answers

Cant' agree with the nikis' answer

Timer and AlarmManager are solutions addressed to satisfy different needs.

Timer is still a "task" that means this is a thread of your application that means that some component of your application must be running on device to keep timer alive. If you set timer for 10 minutes events - you can't be sure if your application will not be disposed by system in some moment. If device will be turned into the sleep mode your timer can be stopped. To prevent behavior like that you have to use PowerLock's and drain battery

AlarmManager is system service (runs outside your application) that means that the pending intent will be sent even if your application is killed after setting the alarm.

Some examples: You have to blink some "led" on the view every 1 s - use Timer - you need it only when application is in foreground, there are short intervals - no point in using AlarmManager for task like that.

You have run some task once after 10 s - Handler.postDelay(); will be the best solution for that, and the job will be done on main thread (UI).

You have to check every 10 minutes if there is some new content on device that you are supposed to push to the server - use AlarmManager - your application does not need to be alive all the time, just let system to start job you want every 10 minutes - that's all.

like image 126
piotrpo Avatar answered Dec 10 '22 11:12

piotrpo


In most cases you should definitely use AlarmManager, because (from the docs):

The AlarmManager 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 AlarmManager releases this wake lock. This means that the phone will in some cases sleep as soon as your onReceive() method completes.

Although you don't need to fire any event while screen is off, AlarmManager still saves the battery by grouping alarms, when you use setInexactRepeating (but this is not important for you, because your interval is 10 minutes). And moreover, it can fire an event is app is not running. I vote for AlarmManager, because it's good practice, but considering your conditions, you can leave Timertask.

BTW, you can also use Handler, which I believe will be the best choice.

like image 45
nikis Avatar answered Dec 10 '22 12:12

nikis