Android background jobs to sync with web service

Could you tell me what is the right way to do synchronization tasks in Android (for example, if I have about 5 tasks)?
Note! By sync job, I mean a thread that runs in the background and sends some data (e.g. analytics) through a web service ...

For more information, please read the more detailed description:

I have a task to implement some background jobs that will synchronize some data with a calming web service. Some of the tasks should be scheduled periodically with a certain delay. If there is no Internet connection, I just cache the data, and later, when the connection reappears, I try to start the tasks. Considering that creating new threads is quite expensive and especially in mobile development, I use a pool of cached threads (ExecutorService), and every time some actions are requested for processing, I try to reuse threads. I do not use AsyncTask because I replaced it with this Executor service (Executors.newCachedTreadPool) and it is convenient for me because I do not need to create many AsyncTasks when reusing threads from ES ... To support scheduled tasks, I use a different pool threads (ScheduledExecutorService) and use Callable, because I need to see the result of execution. I have complex logic here ... So, when a certain action is taken in the application, the first thread pool (like AsyncTask) will work like AsyncTask, the advantage is that I do not create new threads but I return them. This will not block the main thread of the user interface. He will delegate to the designated contractor who will do his job. This solution works. And that sounds good to me as I come from the server side, but I am interested to know how it should be done correctly on Android? Is it too complicated for a mobile application? Merci, Serge

+6
source share
1 answer

Use a sync adapter. See http://developer.android.com/training/sync-adapters/index.html . The synchronization adapter runs in the background, it is controlled by the system and is efficiently distributed so that your synchronization does not lose battery power. Best of all, the system will automatically detect the network connection and, if necessary, queue your sync adapter. If you want, you can use several synchronization adapters.

Note that while it seems that sync adapters need a content provider and an authenticator, they really do not.

+10
source

Source: https://habr.com/ru/post/950398/


All Articles