AlarmManager or Handler

2019-08-29 07:12发布

问题:

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:

  1. If you use Handler and want to post a "cancellable" Runnable to it, then you'll have to store references to both the Handler and the Runnable 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 an Application context, or create a Service for this feature. Using Application for this kind of stuff is generally discouraged, and Service is a bit of an overkill.
  2. 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.
  3. I don't see how you can have less code using Handler approach - all you need in order to use AlarmManager is a single method that creates PendingIntent, which is being passed to both set and cancel methods in AlarmManager...
  4. 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.