问题
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 session is defined as period from app open to app close. I don't have to worry about process kill.
What is better to use? AlarmManager or Handler.postDelayed() ?
The targeted platform is android tv so imagine the case is when watching film in context of my app for example.
Personally I first thought to use AlarmManager but I realized it's way more code to produce compared the circumstances. Is handler causing more CPU usage increase ?
回答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.
回答2:
You should definitely use AlarmManager
for this use case. I can think of several reasons right away:
- If you use
Handler
and want to post a "cancellable"Runnable
to it, then you'll have to store references to both theHandler
and theRunnable
in 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 anApplication
context, or create aService
for this feature. UsingApplication
for this kind of stuff is generally discouraged, andService
is a bit of an overkill. AlarmManager
is 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
Handler
approach - all you need in order to useAlarmManager
is a single method that createsPendingIntent
, which is being passed to bothset
andcancel
methods 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.
来源:https://stackoverflow.com/questions/35159127/alarmmanager-or-handler