Skip to content Skip to sidebar Skip to footer

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:

  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.

Post a Comment for "Alarmmanager Or Handler"