Alarmmanager Or Handler
I have specific case to ping my server every 10-60 minutes (it still depends) but only when app is opened. This feature is created to inform that session is still open where sessio
Solution 1:
AlarmManager starts your app in the future when it is not running. So I think Handler.postDelayed() is a more efficient choice if you will only ping the server when the app is open.
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.
See AlarmManager.
Solution 2:
You should definitely use AlarmManager for this use case. I can think of several reasons right away:
- If you use
Handlerand want to post a "cancellable"Runnableto it, then you'll have to store references to both theHandlerand theRunnablein order to be able to cancel the execution (e.g. if user leaves your app). It means that you'll have to either store them in anApplicationcontext, or create aServicefor this feature. UsingApplicationfor this kind of stuff is generally discouraged, andServiceis a bit of an overkill. AlarmManageris the standard API for this kind of stuff. Any other developer reading your source code (or yourself in few months) will have a much easier time understanding the feature.- I don't see how you can have less code using
Handlerapproach - all you need in order to useAlarmManageris a single method that createsPendingIntent, which is being passed to bothsetandcancelmethods inAlarmManager... - As for CPU usage, I'm sure that the scale will be insignificant, therefore it won't matter.
In general, I think that Handler#postDelayed should not be used to control flows that involve user interactions. It just feels wrong and clumsy.
Post a Comment for "Alarmmanager Or Handler"