I have a bound service. For example, the service has a method calculate() which does some really intensive calculation that should continue execution if activity is closed (that's why service is chosen, not the asynctask). And this service returns some result value which should be display on activity when it is opened again.
Question is the following, how to gracefuly avoid ANR error in bound service if it has to return some value?
If you're using Service this doesn't mean you don't need a thread (or AsyncTask). You need actually.
An extract form the Service reference:
Note that services, like other application objects, run in the main thread of their hosting process. This means that, if your service is going to do any CPU intensive (such as MP3 playback) or blocking (such as networking) operations, it should spawn its own thread in which to do that work.
So, I'd just put the AsyncTask inside the Service in order to avoid ANRs.
update:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
You can update your main thread using:
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
Use Thread or asynctask for calculate() on your Service, too.
Related
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.
Why use asynchronous task in android for executing tasks?, task can be execute directly in ui thread. Is there any restriction in ui thread?
Is there any restriction in ui thread?
The main application ("UI") thread drives your user interface. If you tie up that thread doing your own work, while that work is going on, your UI will be frozen. Updates you try to make will not take place until you allow the main application thread to get back to its normal work. Also, touch events from the user will not respond while you have the main application thread tied up.
The problem is that, unless you are told otherwise, any time that Android code calls your code in the form of one of your callback methods, it will do so on this main application thread.
My general recommendation is that the work to be done in any individual callback method (e.g., onCreate(), getView(), onListItemClick()) needs to take well under 1ms. Many such callbacks are invoked as part of UI processing. If you spend too much time, you may "drop frames" (i.e., prevent the UI from updating at the desired 60 frames-per-second rate) and thereby cause "jank".
An AsyncTask is one way of helping to move work off the main application thread, while still making it reasonably convenient to update the UI with the results of that work. Generally, you cannot update the UI from a background thread, though there are some exceptions (e.g., ProgressBar).
A thread is a concurrent unit of execution. It has its own call stack. There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its run() method.
The other is providing a new Thread instance with a Runnable object during its creation.
A thread can be executed by calling its "start" method. You can set the "Priority" of a thread by calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For example, you are calling some web service or download some data, and after download, you are displaying it to your screen. Then you need to use a Handler with a Thread and this will make your application complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each thread has each message queue. (Like a To do List), and the thread will take each message and process it until the message queue is empty. So, when the Handler communicates, it just gives a message to the caller thread and it will wait to process.
If you use Java threads then you need to handle the following requirements in your own code:
Synchronization with the main thread if you post back results to the
user interface
No default for canceling the thread
No default thread pooling
No default for handling configuration changes in Android
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
onPreExecute()
Invoked on the UI thread before the task is executed
doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
Why should you use AsyncTask?
Easy to use for a UI Thread. (So, use it when the caller thread is a
UI thread).
No need to manipulate Handlers.
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data
Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data
(either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI
thread
For the security purpose, if there is any long process ( more than 5 seconds ) going on in UI Thread, Android OS will terminate that application.
So to solve such Exception and for long running operations like downloading data from network, Android has introduce a new class named AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
I checked in several websites but i didn't find an answer to this question.
I have a UI thread that calls a service with an alarmManager at a specific frequency.
and the service by itself calls another IntentService, that starts a Server/client thread. I want to know if it is possible to make the Server/Client Threads communicate with the UI thread?
Thanks a lot for your help.
The IntentService.onCreate() method is always executed on the UI thread. You can create a new Handler instance inside that method and store it in an instance or a class data member of your IntentService implementation. You can use this Handler to post(Runnable) to be executed on the UI thread, or sendMessage(Message) which will be processed on the UI thread by your handleMessage(Message) implementation. I would suggest to stick with post(Runnable) for simplicity.
Update based on your comment:
Assuming your background thread does continuous processing on its own and does not have a looper, the easiest way would be to create a queue (ArrayList<MyLocation> would work for example), and add each new location to the tail of it from the UI thread. Meanwhile the background thread picks the next location from the head and processes it as expected. This is a very simple asynchronous way of communicating between the two threads (and is essentially a simplified version of how Looper and Message work).
However, the main drawback of this approach is that your background thread is always busy thus waisting CPU resources if there are no incoming location updates. The better alternative would be to change your background thread to be a Looper thread and send Message to it. Here's an example of how to Create Looper thread and send a Message to it.
In UI, to perform some background work, I used a separate Thread. But as suggested by others, I am now using AsyncTask.
What is the main difference between a Thread and an AsyncTask?
In which scenario, should I use a Thread or an AsyncTask?
For long-running or CPU-intensive tasks, there are basically two ways to do this: Java threads, and Android's native AsyncTask.
Neither one is necessarily better than the other, but knowing when to use each call is essential to leveraging the system's performance to your benefit.
Use AsyncTask for:
Simple network operations which do not require downloading a lot of data
Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
If you use Java threads you have to handle the following requirements in your own code:
Synchronization with the main thread if you post back results to the
user interface
No default for canceling the thread
No default thread pooling
No default for handling configuration changes in Android
Thread
Long task in general
Invoke by thread.start() method
Triggered from any thread
Runs on its own thread
Manual thread management/code may become difficult to read
AsyncTask
Small task having to communicate with main thread
Invoke by excute() method
Triggered from main thread
Runs on worker thread
Must be executed and created from the main thread
Thread
A thread is a concurrent unit of execution. It has its own call stack.
There are two methods to implement threads in applications.
One is providing a new class that extends Thread and overriding its
run() method. The other is providing a new Thread instance with a
Runnable object during its creation. A thread can be executed by
calling its "start" method. You can set the "Priority" of a thread by
calling its "setPriority(int)" method.
A thread can be used if you have no affect in the UI part. For
example, you are calling some web service or download some data, and
after download, you are displaying it to your screen. Then you need to
use a Handler with a Thread and this will make your application
complicated to handle all the responses from Threads.
A Handler allows you to send and process Message and Runnable objects
associated with a thread's MessageQueue. Each thread has each message
queue. (Like a To do List), and the thread will take each message and
process it until the message queue is empty. So, when the Handler
communicates, it just gives a message to the caller thread and it will
wait to process.
If you use Java threads then you need to handle the following
requirements in your own code:
Synchronization with the main thread if you post back results to the
user interface No default for canceling the thread No default thread
pooling No default for handling configuration changes in Android
AsyncTask
AsyncTask enables proper and easy use of the UI thread. This class
allows performing background operations and publishing results on the
UI thread without having to manipulate threads and/or handlers. An
asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
onPreExecute()
Invoked on the UI thread before the task is executed
doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute()
finishes executing.
onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
Why should you use AsyncTask?
Easy to use for a UI Thread. (So, use it when the caller thread is a
UI thread).
No need to manipulate Handlers.
For further information visit Here
Thread:
Thread should be used to separate long running operations from main thread so that performance is improved. But it can't be cancelled elegantly and it can't handle configuration changes of Android. You can't update UI from Thread.
AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask, you can update UI unlike java Thread. But many long running tasks will choke the performance.
You have few more alternatives to both of them.
HandlerThread/ Handler and ThreadPoolExecutor
Refer to below post for more details:
Handler vs AsyncTask vs Thread
If you have longer tasks which should work concurrently to leverage the CPU cores and shorten time latency, you should absolutely use Multithreading or a Thread:
You can initialize the thread form the Background Thread or (initialization can be possible as Inner Thread) unlike AsyncTask.
You don't need to inherit parent class and override methods (More Clean and Precise).
You can manage Concurrency yourself with multithreading, just read about Volatile and Atomicity.
For publishing on UI, you can use synchronized thread and notify UiThread using UIhandler.
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.