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:
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:
ScheduledThreadPoolExecutor
IntentService
AlarmManager
Runnable
(with postInBackgroundDelayed
/ DelayedRunnable
, or maybe ScheduledExecutorService
?)And I've ruled out the use of:
ScheduledThreadPoolExecutor
, I've read that this is best used when multiple worker threads are needed, which in my case I only need oneAlarmManager
, this will be executed even when the app is not running, while I only need the task to be performed when the app is runningAnd for the rest, which are IntentService
and Runnable
, from my understanding so far:
IntentService
, needed to be started and stopped manually, tasks are invoked by sending an Intent to the service, and then the result is broadcastedRunnable
, like the block used in Objective-C, a specific segment of code to be executed at appropriate timeOther 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!
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 :
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.