Search code examples
androidperformancemobileandroid-sdk-2.3

Execute task in background at application start and for ever - Android


My Application needs to have one (async) task which is always a network operation and the first time a DB query as well.

It needs to be executed with a certain interval amount of time which is not fixed (could be 1 minute or 1 hour or anything in between) and also when the application is not active.

What is the best and the simplest solution in such case between Asynctask/Thread/Service/Alarm/anything not mentioned.


Solution

  • For that you need a service, not an AsyncTask:

    http://www.vogella.com/tutorials/AndroidServices/article.html

    Services persist even after activities are dismissed. Be careful though, draining the battery will anger your users. Also, services can be destroyed if memory runs low, so be careful.

    The scheduling of a task to run in the future should use AlarmManager. The execution of the operation should run in a service since you specify that sometimes it will occur when the app is not active.

    You can also use a TimerTask but it's a little more drain on battery and not as precise as AlarmManager. You can also use a handler to postAtTime

    Here is a good reference:

    difference between timer and alarmmanager

    and another one:

    What is better in Android? Timer or Alarm?

    It really depends on the frequency and use-case. I've used all of these - I view TimerTasks as "keep checking frequently for short time" vs. handlers for "check again in a while" vs. AlarmManager for "I want to keep checking every hour for a long while"