Search code examples
javaandroidandroid-servicethreadpoolexecutorandroid-intentservice

Perform background scheduled repeating task in Android, and differences between IntentService and Runnable


I am an iOS developer and recently started Android development. Currently I need the application to perform a repeating check regarding a remote resource (a JSON file) in the background, which I would like to:

  1. App finished launching
  2. Initiate scheduled repeating task in Application subclass
  3. Application will be noticed if there are any changes in the remote JSON file and handle it accordingly

After doing some research I found that there seems to have many ways to achieve this, while I can rule out some of them, I can't really tell the differences between the rest and which I should use.

I've found that to perform a scheduled repeating task, I can use the following classes:

  1. ScheduledThreadPoolExecutor
  2. IntentService
  3. AlarmManager
  4. Runnable (with postInBackgroundDelayed / DelayedRunnable, or maybe ScheduledExecutorService?)

And I've ruled out the use of:

  1. ScheduledThreadPoolExecutor, I've read that this is best used when multiple worker threads are needed, which in my case I only need one
  2. AlarmManager, this will be executed even when the app is not running, while I only need the task to be performed when the app is running

And for the rest, which are IntentService and Runnable, from my understanding so far:

  1. IntentService, needed to be started and stopped manually, tasks are invoked by sending an Intent to the service, and then the result is broadcasted
  2. Runnable, like the block used in Objective-C, a specific segment of code to be executed at appropriate time

Other than these are there any other differences between them? Is my understanding correct? Are them both appropriate for my task? It it is the case, are there any considerations before choosing which one to use?

Thanks!


Solution

  • For creating long-running background task in Android, you should create a Service in your application.

    Services are executed on the main thread of the application, with the highest priority as Activity, and continue to run even if the user exits the application.

    Services have the following types :

    • Started Services
    • Foreground Services
    • Bound Services
    • Intent Services

    In implementation of the services, you should create another thread, using for example ScheduledThreadPoolExecuter and delegate the work you want to accomplish to that thread.

    For your requirement, you can create a simple service, extending the Service class, and in the onStart() method, create your thread to do the desired work for you.