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).
I am searching through a dictionary in my app, and because it may takes some time, and involves searching through 170,000+ items, and inserting usually about 100 items into a database, etc..., I am trying to make it not hog the main thread. I have read conflicting things about bound services. Do they run on their own thread, or do I have to manually do that in the service? Basically, what do I have to do to run it in the background? I thought this was the whole point of a bound service. Any help would be greatly appreciated!
You can use an AsyncTask class or just start new Thread if you don't want to do it on ui thread
I have in my project services that start only once and inside the service there is a thread that runs every second or so.
And then there is some services that after they finiah their procedure they call stopself and then they are started again for elsewhere.
My question is which of these structures are better for a service and why?
If you often start and finish Service, try using IntentService
It automatically shuts down after work finished.
Developer Guide
What k0sh said. If your service is running, it is using battery. If you don't need it running, stop it and save battery.
The difference between a running service and a stopped service is the likelihood that the process running it will be killed. A running service has a fairly high priority (low oom_adj). Android will try not to kill it off. A service that is not running has no affect on the priority of its owning process. If there is no other reason to keep that process around, Android will kill it, when it needs space.
Even a running service, though, will be reaped, eventually. There is no way to keep a process running forever.
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.
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.