I have an Android application that has a need to perform work in the background and on a separate thread. For my first proof-of-concept I subclassed the Application class and inside onCreate() I spawn a Thread that does the background work. This works just great. However, I just realized that in the past I've used a service for situations like this.
The question is, is there a reason to do work on a Thread spawned from a Service instead of a Thread spawned by Application.onCreate()? The Service is supposed to perform "background" work (it uses the UI thread unless a Thread is used, I know) that is independent of the Activity and can run while no Activity is visible. Using an Application-based thread seems to accomplish all this just as well. By not using a Service it actually removes complexity because the Activity just accesses the Application singleton. As far as I know I have no need to bind to the Service.
Will I get bit by lifecycle corner cases that using a Service would prevent? That's the only concern I have over this approach, but otherwise I'm not sold on the benefits of a Service.
The difference would be if you want the thread to run in the background only when the Activity is running or if you want it to continue to run when the user leaves.
Services are capable of running in the background even when the Activity is no longer available. They are intended to be used when your app should continue to do work without any user involvement in the near future. If you run the Thread in the Service, the thread will continue to run even when the user leaves the app. This can be beneficial sometimes as the user may want you to keep downloading a really large file but doesn't want the app to continue to run in the foreground. Then, a few hours (days, months, years) later the user can re-enter the app to read the file.
If, however, you're using a thread that needs to constantly update the UI based on results, it may be more beneficial to launch it within the Activity since it has no real purpose to run in a Service. It also may be easier in your program for your Thread to talk to the UI if it's in the Activity rather than the Service. (There may be some performance benefits as Android doesn't have to handle yet another Service on it's list, but that's purely speculation on my part. I have no proof of it.)
NOTE: Threads created in Activities will still continue to run even when the Activity quits. However, this is merely because the app is still in memory. The Activity and it's thread are on a higher priority to be deleted from memory than a Service thread when the Activity is no longer within view.
If your application is not either in the foreground, or visible, then it's more likely to be killed off by the system. If you run your code as a service, rather than a thread spawned by a background process, then your task will survive for longer. No guarantees, so you still need to manage the process lifecycle properly, but running as a service is likely to give more reliable results.
See http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
Related
I was going through Bound Service in Android Developer website. I thought I understood the service enough but I just found another way of connecting service through Using a Messenger class especially for local service. There I got confused. Maybe I got the concept wrong.
Here is my understanding of Android Service. You create a service when
You want to do separate jobs in the background.
You want to make it a separate process.
You want to make it run in a lifecycle that's independent of the component that started it.
Confusion is the first item in the list, the definition of the background. Isn't the background a thread or process? I never thought that it can run on the main thread.
Here is the caution of service in the dev pages about.
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.
Questions
Why does one choose to use service if the service function will anyway run on the main thread?
Do we have to write a service only to block ANR even if the time-consuming job is done in the main thread? Assume the service is only for my application.
Are there any practical cases or reasons to use a service as private and running in the same thread?
Application main thread is not always the UI thread. For example, when Activity is stopped, the onStop() is invoked, hence the UI thread is taken away from that Activity and moved to another Activity within the same or a different application. However it doesn't mean the application is no longer active, it can continue working in the background until it is closed either by OS or by user. Then who keeps it running in the background? It is the main thread and not the UI thread.
What are services
In Android, a Service is an application component that can perform
long-running operations in the background on the UI thread. By
background, it means that it doesn’t have a user interface. A Service
runs on the main thread of the calling Component’s process by default
(and hence can degrade responsiveness and cause ANRs), hence you
should create a new Thread to perform long running operations. A
Service can also be made to run in a completely different process.
Unlike Activity components, Services do not have any graphical
interfaces. Also Broadcast Receivers are for receiving broadcast
messages (broadcast, multicast, unicast) and perform short tasks
whereas Services are meant to do lengthy processing like streaming
music, network transactions, file I/O, interact with databases, etc.
When a Service is started by an application component like an Activity
it runs in the background and keeps running even if the user switches
to another application or the starting component is itself destroyed
Why use service
Services are given higher priority than other Background processes and
hence it’s less likely that Android will terminate it. Although it can
be configured to restart once there is ample resources available
again. You should go through the different processes and their
priority/important level in the documentation on processes and
threads. Assigning them the same priority as foreground activities is
definitely possible in which case it’ll need to have a visible
notification active (generally used for Services playing music).
Use IntentService if you don't want to fiddle with managing threads on your own. Otherwise, use AsyncTasks.
Please read this excellent article to understand more in detail and also read this answer.
Service basically runs in UI thread or main thread.But,if we are going to perform long running operations in service,we need to create a background thread and perform that task.
But why we have to use service?
Now let's think of Music Application.We need songs to be played continuously even if we leave music app.If we use activities,we can't achieve above requirement.So,service helps in these kind of scenarios.Even if the app is not in foreground, service keeps on running and we are able to listen to songs.This is why we use service even though it runs on main thread.
In short, Services runs on the background of the UI thread.
You can perform tasks like client-server authentication or write to a database where the tasks are done in the background with no graphical interface.
But if you're doing a really long processing tasks that could freeze the interface, you use a service on a separate thread.
eg of a Service on a separate thread is IntentService
I'm fairly certain that it's standard practice to handle asynchronous file downloads using a Service and AsyncTask. That way, you can kill the originating activity and go on your merry way. However, when you don't need the lifecycle management, remote process communication, or other major features of a Service, it seems a bit overkill.
Since a Service is still a part of the same process and lifecycle of the overall Application, why not simply run a background thread within the context of the Application (vs Activity, although not necessarily within the extended Application class)? Is there any reason why this would be a particularly bad idea?
I'm fairly certain that it's standard practice to handle asynchronous file downloads using a Service and AsyncTask.
An AsyncTask is useless in a Service, as you have no reason to do anything on the main application thread in a Service. Use an IntentService for downloads, as it gives you a background thread, plus automatically stops itself when there is no more work to be done.
why not simply run a background thread within the context of the Application... Is there any reason why this would be a particularly bad idea?
Because your app will be unreliable.
While a lot of people focus on the independent lifecycle of the service, that's not why you use a service for something like this. You use a service as a flag to the OS that your process is still doing something.
Once you are no longer in the foreground, Android can terminate your process, at will, at any moment. Particularly if there is a lot of memory pressure, this can be within milliseconds of your app leaving the foreground.
However, Android generally prioritizes terminating empty processes (ones with no running activities or services) and activity-only processes, ahead of processes that contain a running service. Here, "generally" means that processes with services will not live forever, but they are far less likely to be terminated quickly.
Hence, using an IntentService is signalling to the OS that you are still delivering value to the user (downloading the file) and that it should leave your process alone, until either your IntentService stops (because the download completed) or your service runs so long that it's probably lost its virtual marbles.
An Application is not a Service. Every process has an Application instance. Having a download be "managed" by an Application is pointless -- you may as well run a bare thread outside of any Context. And, most importantly, nothing tells the OS that you are doing anything meaningful, and so your process can be terminated as soon as you leave the foreground.
However, when you don't need the lifecycle management, remote process communication, or other major features of a Service, it seems a bit overkill.
Writing an IntentService, outside of the manifest entry, is not significantly more complicated than writing an AsyncTask. Invoking an IntentService is not significantly more complicated than invoking an AsyncTask.
When you learn to develop for Android, you learn that if there's any type of process -that takes more that 5 seconds- running inside the ui thread, the system will show the infamous ANR message. That's when they introduce the evil monster... AsyncTask. At first you see this class as your savior, but then you realize it's the biggest problem in development... Handling rotation or ui events becomes so problematic, it's even painful.
What do you guys think about it... are AsyncTasks worth the trouble? Any other method that makes it less of a problem to perform long running tasks regardless of screen rotation?
I guess you'll probably say, hey why don't you just make it a Service... Yeah that's a solution, but then let's go to my real question. Why don't we just use services and stop using AsyncTasks completely... Are they useful at all?
While developing it is always good to choose the suitable component for the execution. You need to clear your requirement and according to it you can choose between a Service or an AsyncTask.
A service is an Android component that lives independently from any other components. Activities may come and go, but services can stick around, if you wish. They serve a number of roles, from managing state that multiple activities rely upon to serving as cron jobs to handling longer app widget updates.
AsyncTask is a class that arranges to do some work off the main application thread. From the implementer and user of the AsyncTask, how it performs that bit of magic is not generally important. In reality, it uses a thread pool and work queue. AsyncTask uses a Handler to help arrange for select bits of work to be done on the main application thread (e.g., notifying the user of progress updates).
For more clarification see the difference between them.
AsyncTasks and Services are not peers. Either might invoke the other, their purposes are different. I have just a few things to add to Lucifer's answer.
A key thing to remember is that if your process is in the background, hosts a Service, and is killed, that Service will be reincarnated at some point. This is not the case for an AsyncTask that may be running in a process when it is killed. This means that work being done in a Service is guaranteed to make forward progress in the future (although its not guaranteed when). If you have work that must be done, better to do it in a Service.
Calls to Service.onStart and Service.onStartCommand happen on the process' main thread. If you block this for a long time, you'll get the same "app not responding" dialog. As a result, an AsyncTask can be a great thing to use inside a Service to do the real work.
I tend to use AsyncTasks initiated from an Activity for things related to the UI. These are often things that aren't required work and whose work can be easily redone in the future. For example, this might be reading a bunch of images off disk or make a calling to a web service to see if the user has any notifications. This work can be done again, and if the UI is destroyed because the process is killed the work probably needs to be done again anyway.
If on the other hand you want to say upload a group of photos to the web as soon as possible, I'd farm this out to a Service which will use one or more AsyncTasks to do it. This is work I want to get done and want to be resumed if it gets interrupted. If you're going to use a Service, consider using an IntentService so that your Service stops when its work is done.
I am confused with android services and java thread.
Please help me to understand in which scenario i should use them.
As per my understanding
Service run in background ,so do thread.
Service is to be used for activities like network operation or playing mp3 in background,so do threads.
So whats actual difference between them and when to use each of them.
Let me give an analogy.
Activities and Service are like projects.
Activities are like external projects. This is what the clients(users) see.
Services are like internal projects. There might be several internal projects for 1 external project or none at all.
You can "pause" external project but the internal project that supports it can still continue.
Main Thread is like the boss in a company
The boss should never be held up by too much work since he shouldn't be late to meetings (UI freezing) or the client(user) will be unhappy.
Threads are like employees in a company.
The more you have, the more things you can do at the same time provided you have enough equipment(CPU speed) for all of them.
Multiple employees can work on the same project at the same time but the boss should really work only on the Activities.
Always: A service of your application is usable not only by other components of your application, but by other applications, too.
A service is for use in not-GUI parts of program.
Mostly: A service is something more independent, than a thread. Service is something more long-living than a thread. Service is something more complex than a thread.
BTW, threads do not run in background only. What runs in foreground, is a thread, too.
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, if your service is killed (e.g. because of memory lack) you can say system to restart it automatically, whenever resources available again. 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 eventually.
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.
Thus when you start a Service, you are telling system something like: "Hi. I'm doing some business here, don't kill me until I finish, please." and Android pay attention to your request.
Services are more analogous to a headless Activity.
The the important piece to understand is that a Service is about managing application lifetime and the ability to keep work running when your Application is not in the foreground (no UI visible). It is also about providing the ability to expose functionality to other apps.
http://developer.android.com/reference/android/app/Service.html#WhatIsAService
Typically when starting a Service you will also start a worker Thread. There are settings in the manifest that can cause a Service to be started in a new Process but generally you do not need to do this, it makes communication with your service more difficult.
Use a just Thread in your Activity when you need to offload work from the UI thread while the application is in the foreground, but this work can stop when you are no longer in the foreground. (It is possible that your app will continue to run when not it foreground but there is no guarantee depending on a number of factors) Generally speaking Android is free to kill your Activity if it is not in the foreground, and if your App process has no Activities or Services it can be killed.
Use a Service with a Thread to do work that will take place while your app is in the background and you want better guarantee about the lifetime.
Use a Service to expose non-UI functionality to other applications.
Android Service don't run in a separate process (by default) and even don't run in a separate thread! It runs in the main thread(UI thread) of the application, therefore if you would like to do something time consuming task in the Service start a separate thread yourself, or use IntentService.
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.
Why we need service is to avoid resource crunch.
For example you opening an application after opening an another application so at the time your app added to the background task.
While opening multiple application, ur app may killed by android system. So if ur app has service it won't be killed by the system because service is higher priority , even it may killed the app has service so that we using constant return type in onStartCommand(). Method. That's START_STICKY,START_NOT_STICKY and DELIVER_INTENT.
Why do I read in the answer to most questions here a lot about AsyncTask and Loaders but nothing about Services? Are Services just not known very well or are they deprecated or have some bad attributes or something? What are the differences?
(By the way, I know that there are other threads about it, but none really states clear differences that help a developer to easily decide if he is better off using the one or the other for an actual problem.)
In some cases it is possible to accomplish the same task with either an AsyncTask or a Service however usually one is better suited to a task than the other.
AsyncTasks are designed for once-off time-consuming tasks that cannot be run of the UI thread. A common example is fetching/processing data when a button is pressed.
Services are designed to be continually running in the background. In the example above of fetching data when a button is pressed, you could start a service, let it fetch the data, and then stop it, but this is inefficient. It is far faster to use an AsyncTask that will run once, return the data, and be done.
If you need to be continually doing something in the background, though, a Service is your best bet. Examples of this include playing music, continually checking for new data, etc.
Also, as Sherif already said, services do not necessarily run off of the UI thread.
For the most part, Services are for when you want to run code even when your application's Activity isn't open. AsyncTasks are designed to make executing code off of the UI thread incredibly simple.
Services are completely different: Services are not threads!
Your Activity binds to a service and the service contains some functions that when called, blocks the calling thread. Your service might be used to change temperature from Celsius to Degrees. Any activity that binds can get this service.
However AsyncTask is a Thread that does some work in the background and at the same time has the ability to report results back to the calling thread.
Just a thought: A service may have a AsyncTask object!
Service is one of the components of the Android framework, which does not require UI to execute, which mean even when the app is not actively used by the user, you can perform some operation with service. That doesn't mean service will run in a separate thread, but it runs in main thread and operation can be performed in a separate thread when needed.
Examples usages are playing music in background, syncing data with server in backgroud without user interaction etc
AsyncTask on other hand is used for UI blocking tasks to be performed on a separate thread. It is same like creating a new thread and doing the task when all the tasks of creating and maintaining the threads and send back result to main thread are taken care by the AsyncTask
Example usage are fetching data from server, CRUD operations on content resolver etc
Service and asynctasks are almost doing the same thing,almost.using service or a asynctask depends on what is your requirement is.
as a example if you want to load data to a listview from a server after hitting some button or changing screen you better go with a asynctask.it runs parallel with main ui thread (runs in background).for run asynctack activity or your app should on main UI thread.after exit from the app there is no asynctask.
But services are not like that, once you start a service it can run after you exit from the app, unless you are stop the service.like i said it depends on your requirement.if you want to keep checking data receiving or check network state continuously you better go with service.
happy coding.
In few cases, you can achieve same functionality using both. Unlike Async Task, service has it's own life cycle and inherits Context (Service is more robust than an Async Task). Service can run even if you have exited the app. If you want to do something even after app closing and also need the context variable, you will go for Service.
Example: If you want to play a music and you don't want to pause if user leaves the app, you will definitely go for Service.
Comparison of a local, in-process, base class Service✱ to an AsyncTask:
✱ (This answer does not address exported services, or any service that runs in a process different from that of the client, since the expected use cases differ substantially from those of an AsyncTask. Also, in the interest of brevity, the nature of certain specialized Service subclasses (e.g., IntentService, JobService) will be ignored here.)
Process Lifetime
A Service represents, to the OS, "an application's desire to perform a longer-running operation while not interacting with the user" [ref].
While you have a Service running, Android understands that you don't want your process to be killed. This is also true whenever you have an Activity onscreen, and it is especially true when you are running a foreground service. (When all your application components go away, Android thinks, "Oh, now is a good time to kill this app, so I can free up resources".)
Also, depending on the last return value from Service.onCreate(), Android can attempt to "revive" apps/services that were killed due to resource pressure [ref].
AsyncTasks don't do any of that. It doesn't matter how many background threads you have running, or how hard they are working: Android will not keep your app alive just because your app is using the CPU. It has to have some way of knowing that your app still has work to do; that's why Services are registered with the OS, and AsyncTasks aren't.
Multithreading
AsyncTasks are all about creating a background thread on which to do work, and then presenting the result of that work to the UI thread in a threadsafe manner.
Each new AsyncTask execution generally results in more concurrency (more threads), subject to the limitations of the AsyncTasks's thread-pool [ref].
Service methods, on the other hand, are always invoked on the UI thread [ref]. This applies to onCreate(), onStartCommand(), onDestroy(), onServiceConnected(), etc. So, in some sense, Services don't "run" in the background. Once they start up (onCreate()), they just kinda "sit" there -- until it's time to clean up, execute an onStartCommand(), etc.
In other words, adding additional Services does not result in more concurrency. Service methods are not a good place to do large amounts of work, because they run on the UI thread.
Of course, you can extend Service, add your own methods, and call them from any thread you want. But if you do that, the responsibility for thread safety lies with you -- not the framework.
If you want to add a background thread (or some other sort of worker) to your Service, you are free to do so. You could start a background thread/AsyncTask in Service.onCreate(), for example. But not all use cases require this. For example:
You may wish to keep a Service running so you can continue getting location updates in the "background" (meaning, without necessarily having any Activities onscreen).
Or, you may want to keep your app alive just so you can keep an "implicit" BroadcastReceiver registered on a long-term basis (after API 26, you can't always do this via the manifest, so you have to register at runtime instead [ref]).
Neither of these use cases require a great deal of CPU activity; they just require that the app not be killed.
As Workers
Services are not task-oriented. They are not set up to "perform a task" and "deliver a result", like AsyncTasks are. Services do not solve any thread-safety problems (notwithstanding the fact that all methods execute on a single thread). AsyncTasks, on the other hand, handle that complexity for you.
Note that AsyncTask is slated for deprecation. But that doesn't mean your should replace your AsyncTasks with Services! (If you have learned anything from this answer, that much should be clear.)
TL;DR
Services are mostly there to "exist". They are like an off-screen Activity, providing a reason for the app to stay alive, while other components take care of doing the "work". AsyncTasks do "work", but they will not, in and of themselves, keep a process alive.