Search code examples
androidalarmmanagerandroid-pendingintent

Android:Is it possible to do all updating tasks with AlarmManager


I have used background service in for updating tasks like playing with web server frequent times(sending Geo-Location data or send/get web data time-wise) in my android apps and also I have faced many problems(slow process, application hang) for this.

But In my current application I have used the AlarmManager followed by PendingIntents for some tasks which worked well. So I think its good if I replace each updating tasks which use service with AlarmManager followed by PendingIntents.

Is it the right way or I am going doing a big mistake ?

All kind of suggestions are appreciable. Thanks in advance.


Solution

  • Services and alarms scheduled with AlarmManager serve different but complementary purposes at times. When you schedule an alarm with one of the set methods, the alarm will be triggered at the specified time and you should handle it on a BroadcastReceiver. This means that your handling has to be responsive and cannot have asynchronous operations. According to the docs:

    A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active. (...) Anything that requires asynchronous operation is not available, because you will need to return from the function to handle the asynchronous operation, but at that point the BroadcastReceiver is no longer active and thus the system is free to kill its process before the asynchronous operation completes.

    In case you want to handle more complex operations, it is advised to start a service for doing so. Even if you use the more recently available goAsync() call on the receiver, you are still expected to be responsive:

    This does not change the expectation of being relatively responsive to the broadcast (finishing it within 10s)

    So it ultimately depends on what you are trying to achieve, when to use each of these or combine their use.