When to use a thread / service in Android? - java

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.

Related

I want to run a thread in my application that will run for the entire time while the user is online. I cant choose variant

I want to prevent the thread from stopping during the transition between activities and call this thread during the start of my application. I have one option and I would like to share it. So far, I have stopped at writing an android service in which to include the beginning of the stream that, I need to perform. And then call it in the class inherited from the application class. It is important to note that my thread will send certain data to the database every minute. Perhaps you can advise a more reliable and popular way to solve the problem.
Threads don't stop between Activities. That would be impossible to do safely- threads cannot in general be safely stopped by anyone but the thread itself without risk of data corruption or deadlock. So Android doesn't even try. (You can cancel a thread from another thread, but that works by setting a flag and hoping that the thread you want to cancel looks at it occasionally to honor it.)
The real problem is twofold
1)How do you know if the thread is already running so you don't launch it again. This is solvable in a variety of way.
2)Do you want the thread to work when the app is in the background? This is the real problem, because Android kills background apps regularly, which will end the thread. There is no reliable way to make a thread run constantly in the background in Android. Here your best bets are either a foreground service running to keep the app active, or to not use a thread and make your app even t driven (for example, setting a repeating alarm for every 15 minutes and running then).

Performing Background Tasks – alternative to AsyncTask?

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.

Service onStartCommand and onCreate executed from the same Thread as Activity's onCreate

Android OS never stops surprising me. I wish i'd know whats the rule opon which they decide weither to kill your Thread or not while your app is on background. This is very confusing, at first i was sure that they run Services code on special service threads, and any thread created from the Service Thread is not eliminated when app goes to the background, but then when i Log Thread.currentThread() i see that both Activity's code and Service's code runs on the same main Thread, while as documented, services can run on background while activities cant.
How is this whole thing work? how do they decide which Thread to kill and which not? how do they decide weither an Object is in use or that its memory can be freed? at first i expected it to work like in standart Java enviroment but they got everything changed in an unclear and not very documented way...
anyone here can give me a reference to a good article about this issue or even better can explain this to me?
For starters, when dealing with Services you should probably read the Service doc. A relevant line from there is:
Note that services, like other application objects, run in the main thread of their hosting process.
All of this is quite well documented actually. The Android OS does not kill specific threads, only entire processes. You can read more of this in the Process Lifecycle section of the same document.

Android background jobs for synchronization with a web service

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.

Android Service Initialization. Should I use threads?

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.

Categories

Resources