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.
Related
I am new in android, i use to work with asynk task mostly, there is Handlers also, when read differences between thread, asynk task and Handler i confuse why should not use only Handler if handler can do every thing just for one difference i.e. Asynk task initialize on UI thread and Handler can initialize from any.
Please some give me the situation when to use Asynk task and when not and why? same with Handler?
You are mistaking with handler. Handlers are used to communicate between two threads. To achieve function what Asynctask is used to achieve you have to use handler and thread together as thread will be used to do background processing while handler will be used to update UI accordingly. While both of this tasks can be performed by asynctask itself.Hope this clears a thing a bit.
Also you can refer this link for further clarifications Handlers and Thread
AsyncTask is used to run in background without interrupting the UI thread (main thread), Handlers run on the main thread and are good options to communicate the UI components from another thread for purposes like UI update operations but if you use it to do a expensive process on, your main thread will be blocked until the job is done.
I personally use Handlers as a message management part to keep up my UI components considering the app events and use a AsyncTask to run a process in background along a Fragment or Activity lifecylce.
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.
Is it a must that we have to initiate and execute asyctask from UI thread.Is it correct if i use asynctask for a webservice access(long running) from a non ui thread.
sorry if my query is wrong.
In my app i have to run around 10 webservices and have to show the result on ui .i am confused which approach will be good asynctask,intentservice or creating thread for each webservice call and making it to run parallel.
There are a few threading rules that must be followed for AsyncTask to work properly:
The AsyncTask class must be loaded on the UI thread. This is done automatically as of JELLY_BEAN.
The task instance must be created on the UI thread.
execute(Params...) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Further Details
In my personal opinion, I would suggest using AsyncTask as it is highly optimized for running background tasks and exploit benefits like multicore processor.
Yes, asynctask needs to be run from the UI thread.
I'd suggest to use multiple threads/runnables. You'll also need to implement a handler in your main activity class to listen to the responses from the threads.
You can go with either thread or asynctask.
AsyncTask provide you methods to manage Ui changes methods before starting background task and after finishing backgroung task or getting its progress.
It depends on your architecture requirement.
while working on thread in android I came across runnable and handler. My question is, what is the better option to use AsyncTask or Thread (or Runnable) for multi-threading. I found using AsyncTask very easy and efficient.
As far as my concern ,if you need to run short operations you can use AsyncTask.To keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.You can also refer http://developer.android.com/reference/android/os/AsyncTask.html
Async Task
AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
However, there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Runnable
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler
Handler is more transparent of all and probably gives you more freedom; so if you want more control on things you would choose Handler.
Handler is a special class that can handle messages that are sent to the handler's thread.
AsyncTask's advantage is that it can perform actions in a different thread than the UI thread using the doInBackground functions,and then return the output of the processing to the UI thread using the onPostExecute function. This is very important because only the UI thread can be used for UI related functionalities.
Asynctask is more Efficient as it has Functions onPreExecute(), onPostExecute(), onProgressUpdate() and doInBackground() functions.
The doInBackground() function runs in a seperate thread where we can run intensive operations and you can update the progress of the running operation using onProgressUpdate(). and onPostExecute() function is called after the doInBackground() function finishes where you can dismiss the progress dialog if used. The Advantage here is you need not create a seperate thread as this class has functions for doing that.