Could you pease tell me what is the correct way to do the synchronization jobs in Android (e.g. if I have about 5 jobs)?
Note! By synchronization job I mean a thread which runs in background and sends some data (e.g. analytics) via a Web Service...
For more details please read a more detailed description:
I've got a task to implement some background jobs which will synchronize some data with a restful web service. Some of the jobs should be scheduled periodically with a specific delay. If there is no internet connection then I simply cache the data and later when the connection reappears I try to run the jobs.
Taking into consideration that creating new threads is quite expensive and especially on mobile development, I'm using a cached thread pool (ExecutorService) and every time some actions are requested for processing I'm trying to reuse the threads. I don't use AsyncTask because I've replaced this with this Executor Service (Executors.newCachedTreadPool) and its convenient for me because I don't need to create many AsyncTasks as I reuse the threads from ES... In order to support the scheduled jobs, I use another thread pool(ScheduledExecutorService) and use Callable because I need to see the execution result. I've got a complex logic here... So, when a particular action is done in the app, the 1st thread pool (is like the AsyncTask) will work like an AsyncTask, the advantage is that I don't create new threads but I reus them. This will not block the UI's main thread. It will delegate to the scheduled executor which will do its job.
This solution works. And it sounds good for me as I'm coming from server side, but I'm interested to know how this must be done correctly on Android? Is this too sophisticated for a mobile app?
Merci,
Serge
Use a sync adapter. See http://developer.android.com/training/sync-adapters/index.html. A sync adapter runs in the background, it's managed by the system, and scheduled efficiently so that your sync doesn't waste battery power. Best of all, the system will automatically detect network connectivity and queue up your sync adapter if necessary. If you want, you can use multiple sync adapters.
Notice that although it seems that sync adapters need a content provider and an authenticator, they really don't.
Related
As the title says, I am having some multi-threaded issues.
I am using JavaMail in order to construct an e-mail app with fully supported sending/receiving e-mails.
I have a method for fetching e-mails from server, which gets started with a service every x secnds. The issue is, when I first log in with an account and start fetching e-mails from server, I can't send messages until all emails are fetched and thread is closed.
I am not well acquainted with AsyncTasks, but both of the classes (fetch and sendmail) are separately declared, so I am not sure as to why they're interfering with each other.
By default, AsyncTasks run on a single background thread.(!!) So your send task probably gets queued up to run after all the fetches take place.
You can choose to run AsyncTasks on a threadpool using AsyncTask.executeOnExecutor, supplying THREAD_POOL_EXECUTOR as an argument. So now your send task will get queued after all the sends complete on the N available threads in the threadpool.
That being said, long-running I/O operations should probably be run on dedicated threadpool(s), not on THREAD_POOL_EXECUTOR, since the default thread pools are intended for use by short-running tasks. You will end up starving UI-related use of the standard thread pools if you don't. You really want dedicated pool of two or three or four threads for the receive, and probably a separate one or two or three threads for the sends.
For what it's worth, AsyncTask dates from the Dark Ages of Android, has suffered repeated abuse from the Android development team, and is now officially deprecated. (Hooray!) The AsyncTask's template arguments and executor syntax are just a bad idea from the start; and it's far too easy to make mistakes using it. Google now recommends you use java.util.concurrent instead.
ps. To be fair, AsyncTask was designed in an age when cellphones were pathetic things with 320x200 displays, one CPU, where having two whole threads was a big deal. java.util.concurrent is much better.
I want to have various asynchronous threads in app like around 5-10 threads for background tasks which can be long running (like streaming) and I am also updating the UI to post some results if necessary.
From what I have heard that AsyncTask has problems with:
Long running tasks,
Having poorly being tied to Activity life cycle,
Device orientation problems, and
Memory leaks and so on.
So, I am looking an alternative (possibly without using any third party libraries) which doesn't have these above problems.
Should I be better off with using Simple Java Threads? I don't mind using them given that they won't give any problems that are with AsynTask.
In most scenarios AsyncTask should suffice the requirement. However there are scenarios where AsyncTask can't be used. ie AsyncTask manages a thread pool, from which it pulls the threads to be used by task instances. Now the thread pools assume that they'll get their threads back after a reasonable period of time. So in a scenario where you do not know how long you'll need the thread you can't use an AsyncTask. And as of Android 4.4 , the size of thread pool can grow only to : (no of CPU cores * 2) + 1. So on a dual core processor, the maximum number of threads you can create is limited to 5.
So, I am looking an alternative (possibly without using any third party libraries) which doesn't have these above problems.
Coming to the alternatives to AsyncTask, these are the available options:
Handler
Runnable
Now there are cons to all background threads no matter how beautifully illustrated they are, few include:
The possibility of user's interaction while the background thread is processing. If the work that the background thread performing is altered, you'd need to communicate it back to the background thread. java.util.concurrent has many classes to help in these scenarios
The possibility of the process itself being killed while the thread is performing tasks. So in these cases instead of using an AsyncTask or the simpler Thread a Service or IntentService would be an ideal option.
The possibility of an error occuring inside the background thread, such as retrieving data from server while connectivity is lost, you'd need to manually shut down the background thread.
In short: Whichever option you choose, you'd need to manually handle
all corner cases for the efficient and splendid working of the app.
PS:
[Citation] : The busy coder's guide to Android development v5.8 by #Commonsware which is released under the Creative Commons Attribution Non-Commercial Share Alike 4.0 License
Long running tasks,
Having poorly being tied to Activity life cycle,
Device orientation problems, and
Memory leaks and so on.
Simple java threads are not going to solve any of these problems. Specially, memory leaks.
If you just want to load data in background, you can think about Loaders. They cache the data application wide and fit nicely with activity/fragment life cycle.
Alternately, you can go through this article to know about services (if you don't know already) and see if they are suitable in your scenario.
I would first suggest to use the above mentioned components,
Handlers
Runnables
If the operation is long running then you can go for service as it runs continuously. You said
which can be long running (like streaming)
If you are streaming over some audio or video then it is best to use a service either a normal Service or an Intent Service depending on your requirements.
You can destroy the service when ever needed or let the Android system do it when required.
Hence I would suggest you to use a Service in such a scenario.
I have a user workflow where at a specific time a webservice is called, and the results are presented to the user.
According to the search request and the queried results, I want to perform some database updates and statistic logging.
As the workflow pauses while the webservice is requested, I thought about creating some kind of background thread that performs these database actions, while the user can already continue the workflow without having to wait for database actions to complete.
Do you think this is a good practice? How could I create such onetime running background threads?
If you only want to run in the background, then an Executor service is a good solution.
If you need to ensure that queued requests survive events like a server restart, then you need a persistent queue like a JMS Queue. There are some nice, free open source JMS implementations that serve this purpose.
If service call teakes little time (say 1 or 2 seconds) then it is a waste of time to develop such feature.
If it takes significant amount of time you should do this in background.
I'm coding a simple Android Service which will do some File IO intensive job.
The service will be running in the background for a while, and initializing the service will take a while. (It'll take longer as there are more files to scan).
So I thought that I should use a thread to initialize the service, since services are run on the UI thread. Will this be a good idea?
Should I wait for the initializing thread to end by calling the join() method and execute any more less time consuming jobs?
The reason I'm trying to use threads for initialization is because I don't want my activity starting the service to hang when my service is starting up.
Update
Okay, The reason I'm trying to use a service is to provide a means for an external client(such as a web browser, or a PC client) to access the files of my android phone. I also want to allow the service to keep running when my application goes to the background.
Do you really need a Service? If your code will do a lot of work in the Service it is always a good idea to do it in a thread. If you do not really need the Service, think of using an AsyncTask.
Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.
http://developer.android.com/guide/components/services.html
Take a look at IntentService. It automatically runs in a separate thread and exits when it finishes its work. Seems like it would be appropriate for your situation.
When should a thread or a service be used?
Should they be used for authentication? For instance, in my app I was considering using a thread or service (I am authenticating via Active Directory.)
Do you have examples of when each would be used?
Update: It seems the Android documentation includes a corresponding clarification now, see http://developer.android.com/reference/android/app/Service.html#WhatIsAService.
Original answer:
In Android, a Service does not provide any concurrent execution ("run in background"). It is actually more of a simple Java object which merely is instantiated (and managed) via the Android system instead of your application via new.
The most important property of a service is therefore not about deferring workload; this can be achieved with simple threads.
What makes a service object special is that it is registered with the Android system as a service. This let's the system know that this object provides some sort of service and should be kept alive as long as possible, or until it is stopped. Normal application threads do not have this special meaning to the Android system and will be terminated much more generously at the discretion of the system.
So, if you need some background activities to go on only while your application/Activity is active, a thread can do what you need.
If you need a component that keeps active will not be purged even when, after a while, the Android system decides to remove your Activities from memory, you should go for the service, or even a "foreground service", which is deemed even more important by the system and even less likely to be terminated to reclaim resources.
Of course, if desired, a Service object can also be made to contain one or more Thread instances which could then live as long as the Service object itself.
Edit:
Oh, plus: A service is, of course, the way to go if you want to provide some service(s) to other applications, which can "bind" to a service only.
A thread should be used in a long running process that would block the UI from updating. If it's more than a second or two you might want to put it into a background thread and notify the user with a dialog or spinner or something. If you lock the UI thread for more than 5 seconds the user will be prompted with a "kill or wait" option by the OS.
A service does not run on separate thread, so it will block the UI, but you can spawn a new thread within a service. A service is used more for something that should happen on an interval or keep running/checking for something when there is no UI shown.
Just look at this nice post Android Thread Constructs(Part 4): Comparisons
.
or Difference between Service, Async Task & Thread?.
Use service if you need something that is either used by other applications or outlives your application activities. The good example of service is file transfer that may take long time and you don't want to force user using your application during this time. Use thread (usually via AsyncTask or similar) in other cases.
For authentication purposes AsyncTask seems like a good choice.
I believe the main difference is about Android system attitude. Service is a part of android infrastructure, so android recognizes service as a working part of application and considers killing service as a last option. Moreover, you can tune up service priority in order to do it as important as foreground activity. As for threads, android does not recognize a thread as important part which must be kept. So usual threads has much more chances to be killed.
For instance If you have an activity which start a working thread and then go background, as android do not recognize thread as a working part, it may think that application do nothing, because no activity or service running and kill the whole app, including the working thread.
As per Android Developer Guide (http://developer.android.com/guide/components/services.html#Basics) :
A service is simply a component that can run in the background even when the user is not interacting with your application. Thus, you should create a service only if that is what you need.
If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create a thread in onCreate(), start running it in onStart(), then stop it in onStop(). Also consider using AsyncTask or HandlerThread, instead of the traditional Thread class. See the Processes and Threading document for more information about threads.
Remember that if you do use a service, it still runs in your application's main thread by default, so you should still create a new thread within the service if it performs intensive or blocking operations.