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
Related
I've built a music player which is running on a Service.
I'm preforming various actions as play, pause, next song, previous song etc through a binding to the service from my activity.
It works totally fine.
So to my question:
Is it ideal to put the service on a new thread? I know Service run by default on Main/UI thread.
If not, how do I know when to actually put something on a new thread? Can I put the whole Service instance on new thread or just a part of the code in the Service?
I guess this is called a long running service, shouldnt that be on a own thread to not block the UI?
When debugging I can see this in Logcat: I/Choreographer(691): Skipped 60 frames! The application may be doing too much work on its main thread...
That got me wondering too! :o
As my title says, I'm very confused about this!
You are right, Services are not threads (they do not create a different thread).
When started form an activity they would block the main/UI thread fi running long operations.
you can use IntentService - which start their own thread to perform background long running operations - but that would probably suits a download file task or long running calculation better than playing music.
note that IntentService creates and destroys the thread by itself (when the work is done).
Another option would be to create you own thread manually.
That said, I would consider this article:
http://developer.android.com/guide/topics/media/mediaplayer.html
It talks about a service in the foreground using startForeground() which adds a notification to the status bar, letting the user be aware of the fact that the service is running - as well as promoting the service so it won't get destroyed in case of low memory conditions (it could be - but it will probably be the last one to be closed).
the example is about running media player while taking the main thread blocking into consideration as well as handling system events to pause and play music as expected (using BroadcastReceiver )
Also note this:
http://developer.android.com/guide/components/services.html
Should you use a service or a thread?
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.
I am looking for what service should be used in android applicaton.
Docs says
A Service is an application component that can perform long-running operations in the background and does not provide a user interface.
I have read this thread Application threads vs Service threads that saying same services are for running operation in background.
But here this can be done using Thread also. Any difference between them and where you should use them
UPDATE based on latest documentation:
Android has included in its documentation on when you should use Service vs Thread. Here is what it says:
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.
Another notable difference between these two approaches is that Thread will sleep if your device sleeps. Whereas, Service can perform operation even if the device goes to sleep. Let's take for example playing music using both approaches.
Thread Approach: the music will only play if your app is active or screen display is on.
Service Approach: the music can still play even if you minimized your app or screen is off.
Note: Starting API Level 23, you should Test your app with Doze.
Android Documentation - Services
A Service is meant to run your task independently of the Activity, it allows you to run any task in background. This run on the main UI thread so when you want to perform any network or heavy load operation then you have to use the Thread there.
Example : Suppose you want to take backup of your instant messages daily in the background then here you would use the Service.
Threads is for run your task in its own thread instead of main UI thread. You would use when you want to do some heavy network operation like sending bytes to the server continuously, and it is associated with the Android components. When your component destroy who started this then you should have stop it also.
Example : You are using the Thread in the Activity for some purpose, it is good practice to stop it when your activity destroy.
This is the principle i largely follow
Use a Thread when
app is required to be visible when the operation occurs.
background operation is relatively short running (less than a minute or two)
the activity/screen/app is highly coupled with the background operation, the user usually 'waits' for this operation to finish before doing anything else in the app.
Using a thread in these cases leads to cleaner, more readable & maintainable code. That being said its possible to use a Service( or IntentService).
Use a Service when
app could be invisible when the operation occurs (Features like Foreground service could help with operations being interrupted)
User is not required to 'wait' for the operation to finish to do other things in the app.
app is visible and the operation is independent of the app/screen context.
Reference from https://developer.android.com/guide/components/services.html
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().
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.
My Approach for explanation is simple:
Create a thread when you are in the activity and want to do some background operation with frequent communication with the main thread.
Alert- Don't create too many threads as 1 thread is equal to 1 processor thread. If you want to do parallel processing with threads(multiple) try your hands on Executors
Now you want long running operations with less interaction with UI then go for Service. Keep in mind service runs on UI thread. But now you want the processing should be done in background thread, then go for Intent Service.Intent service maintains their Thread Pools and do not create new threads and runs your tasks serially.
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.
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
What are the advantages/disadvantages in placing a lengthy network access code in a thread in an activity or a thread in a service? How would it affect the application? I am writing a streaming audio player and from what I've read so far putting the code in a service will still end up blocking the application so a new thread is needed, does anyone know if it makes more sense to put this piece of code in a service.
Yes, a blocking operation in a Service will still block the application. Despite first appearances, Services are not simply for running tasks in the background. They are for running tasks with a lifecycle that is independent of the Activity lifecycle (IE, they may continue after the Activity is closed).
A Service that starts when an Activity starts and ends when the Activity ends is useless.
In your case, where you are streaming audio, you may want to stream audio even after the user closes the Activity, in which case, you should use a Service, but you'll still need a thread (or an AsyncTask) for blocking tasks.
From my experience (1+ years developing Android), there is no difference between running a new thread in a service or in an activity.
Try not to keep a reference to the Activity in the new thread - use the application context.
Also, the service's life-cycle didn't help at all because some methods are not guaranteed to be invoked :(
The only difference may be that the service can be destroyed without destroying the app completely - thus potentially destroying the new threads.
Why potentially? because on the practical side, this doesn't happen. The app ALWAYS gets killed without killing the service before that, meaning: the local service mechanism is useless!!!
Remote service is a different discussion - I was referring only to "where should I run a new thread?".
Good luck!!!
The difference is how the system manages your application process lifecycle. Running threads don't affect the application process lifecycle, but a service does.
To determine which processes should be killed when low on memory, Android places each process into an importance hierarchy based on the components running in them and the state of those components. If your app doesn't have a visible activity or a foreground service but has a background service, it's categorized as a service process and will be kept alive while there less priority cached processes exist. But if the app has neither a visible activity/fragment, foreground service nor a background service, it's categorized as a cached process and can be killed at any time to free system resources, whether it has a running thread or not.
But do not rush to create a background service, there are more modern approaches to deal with background tasks nowadays. Consider alternative solutions described below and in the background processing guide and keep in mind all restrictions associated with background services.
If a thread executes a task which result is required only by an activity, the thread lifecycle should be bound to the activity. In such a case no services are required. It's so called immediate tasks, ViewModel + Kotlin Coroutines + ViewModelScope is a great way to deal with it, see Guide to background processing for more details about different kinds of background tasks.
If the task should be completed whether the user closed you app or not and it's not required to execute it immediately, consider using WorkManager which is a great way to deal with such deferred tasks. See Android Work Manager vs Services? for more details.
Otherwise, if you have an immediate task which lifecycle isn't bound to an activity/fragment, may be a foreground service would be the best choice, especially in case of an audio player. There are some limitations considering background services since Android 8, the system stops an app's background services in several minutes after the app is closed, so it's not a place for a long running task.