What should be used in service to move away from UI thread?
For both Started Service and Bound Service
Loader
Asynctask
Simple thread
Robospice Library
Or something else
I want my service to keep on running even if the app is in background.
I want service to run indefinite time.
Thanks.
Use IntentService. It is a subclass of Service. It automatically runs the code in the background thread. And it clears itself up after the execution completes. You don't have to stop the IntentService.
If you have to run single long task and stop service after that, you should use IntentService - it run on separate thred and stop itself after job is done. From your descriptin it seen like you want Service running indefinite time. For that you should use RxJava library. It has many advantages for performing concurrent operations, see docs for more details, among those;
Eas two thread pools and scheduler for main thread;
Easily allow synchronizing concurret tasks - you can execute one task, wait for another, etc. without using pure java's locks.
You can run job on one thread, then process results on another thread, etc;
You can process results in reactive ways;
You can create your own scheduler from HandlerThread and use single thread for all your tasks
Related
In a recent answer, I read
A service does not run on its own thread, it runs on the UI thread
I've read similar statements in many other service-related questions.
If I call startService() from an Activity, will the Service run on the Activity's UI Thread or does it spawn a new process with it's own UI Thread?
If it runs on the Activity's UI Thread, doesn't that risk making the Activity unresponsive?
Yes services does run on main thread , About ANR(application not responding ) concern , there will higher chances of ANRs if your service is doing a long processing work using CPU so the official docs also recommends to use Worker Threads for efficiency. docs
You must read the caution paragraph in the docs to confirm
If your task is one time shot then Use IntentService which implicitly use threading mechanism for processing but IntentService will destroy itself automatically when the task is done so you will have to start it again for the next time and so.
android:process : Using this to start a service in an another process will cause usage of more memory. This will cause creating two processes for your app in separate heap memory space which also require other maintenance as well.So this is rarely used and i would not recommend to use this for a regular service task.
If I call startService() from an Activity, will the Service run on
the Activity's UI Thread or does it spawn a new process with it's
own UI Thread?
If it's a Service (not an IntentService), it will run on the main Thread of your app's process, as long as you do not define it as a separate process explicitly (by adding the android:process tag in the Manifest).
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
Yes it does, if you perform CPU intensive/blocking operations.
To prevent that, you can either start new Thread(s) from your Service, or use an IntentService, which will automatically spawn a new worker Thread for its work.
From the Services Docs it clearly explains your answer.
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.
In a recent answer, I read
A service does not run on its own thread, it runs on the UI thread
This is just plain wrong. A Service is an object (an instance of a class). It doesn't run on any thread, it doesn't run at all. It just "is". The methods of the Service may run on any thread, depending...
Specifically, the lifecycle methods of a Service (onCreate(), onStartCommand(), etc.) that are called directly from the Android framework run on the main (UI) thread, which may or may not be the same thread that called startService(). However, a Service can (and usually does) start other background threads, as many as it needs to, to perform the necessary work.
If I call startService() from an Activity, will the Service run on the
Activity's UI Thread or does it spawn a new process with it's own UI
Thread?
See above. If you want your Service to run in a separate process, you can do this by specifying android:process=":service" in the <service> declaration in the manifest. By default, services run in the same process as the other components (Activity, BroadcastReceiver, etc.) of your application.
If it runs on the Activity's UI Thread, doesn't that risk making the
Activity unresponsive?
That depends on what your Service is doing! Obviously if your Service is doing a lot of compute-intensive processing on the UI thread it will make your app unresponsive. If your Service is doing I/O on the UI thread, Android will usually throw exceptions (in more recent versions of Android). This is the reason that services usually start background threads to do work. However, if your Service is lightweight, then there is no reason why methods of your Service cannot run on the UI thread. As I said, it depends...
IntentService runs on the background thread, so, if you want to do one-off tasks then use that.
So I have gone through the developer site:
https://developer.android.com/training/articles/perf-anr.html
So I came to a conclusion :avoid intensive tasks via worker thread. So should use Asyctask, Intent Service and Handlers.
Also these three tasks have some limitations:
Asynctask:
It could not be used for long running operations
Cannot be used when using multiple asynchronous operations and and the need for UI change, will become more complicated
IntentService
Works requests run sequentially.
Operation running cannot be interrupted
Now keeping this in mind, as Handler and IntentServices could be used for long running operation.
can anybody help me with the difference between Handler and IntentService ?
Like when should I use Handler and when IntentService and which is better to use?
Also what is the best approach to run request asynchronously?
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 have a lot of async tasks in my activity, and I need to override AsyncTask for every call to do it async.
Can I replace all the AsyncTasks with BoundService + AIDL or I need to do it only with AsyncTask?
Service run in background but still run in main thread (AKA. UI thread), you will get ANR exception. according to API here:
Most confusion about the Service class actually revolves around what it is not:
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
You can use service, but you still need implement your thread logic in either service or activity,if you want something run in a separate thread.
Service is a daemon, AsynkTask is background thread
What is the difference between Service, Async Task & Thread. If i am not wrong all of them are used to do some stuff in background. So, how to decide which to use and when?
Probably you already read the documentation description about them, I won't repeat them, instead I will try to give answer with my own words, hope they will help you.
Service is like an Activity but has no user interface. Probably if you want to fetch the weather for example you won't create a blank activity for it, for this you will use a Service.
A Thread is a Thread, probably you already know it from other part. You need to know that you cannot update UI from a Thread. You need to use a Handler for this, but read further.
An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods, and there are three methods that run on UI thread, which is good to update UI components.
I am using Services, AsyncTasks frequently. Thread less, or not at all, as I can do almost everything with AsyncTask.
This is the easiest answer for your question
Thread
is an unit of execution who run "parallel" to the Main Thread is an important point, you can't update a UI component from the any thread here except main thread.
AsyncTask
is a special thread, which gives you helper methods to update UI so basically you can update the UI even AsyncTask will run on a background thread. Interprocess communication handling is not required to be done explicitly.
Service
solve the above problem because it live separate from the activity that invoke it so it can continue running even when the activity is destroyed, it run in the Main Thread(beware of ANR) use a background service (extend IntentService it create the worker thread automatically for you). Service is like an activity without UI,
is good for long task
Few more information I wish someone had told me a few days ago:
You can share global variables - such as threads - between Activities and Services.
Your application together with all its global variables will not be wiped out as long as there is an Activity or a Service still present.
If you have an instance of a Service in your app and the OS needs resources, it first kills your Activities, but as long as there is the Service, the OS won't wipe out your application together with its global variables.
My use case is like this: I have one thread in global space that is connected to a server and an Activity that shows the results. When user presses the home button, the Activity goes to background and a new Service is started. This service then reads results from the thread and displays information in the notification area when needed. I don't worry about the OS destroying my Activity because I know that as long as the Service is running it won'd destroy the thread.
In short, Service for time consuming tasks, AsyncTask for short-lived tasks, Thread is a standard java construction for threads.
From developer's perspective:
Thread: Used to execute the set to codes parallely to the main thread. But you cannot handle the UI inside the thread. For that you need to use Handler. Hadler binds thread Runnable with Looper that makes it a UI thread.
ASyncTask: Used for handling those tasks that you cannot make to work on the main thread. For example, an HTTP request is a very heavy work that cannot be handled on the main thread, so you handle the HTTP request in the ASyncTask It works parallelly with your main thread Asynchronously in the background. It has a few callback methods that are invoked on their corresponding events.
Service: Works in the background under the same Application process. It is implemented when you have to do some processing that doesn't have any UI associated with it.
service is like activity long time consuming task but Async task allows us to perform long/background operations and show its result on the UI thread without having to manipulate threads.