Thread ,UI thread, Worker Thread, Async Task - android

I am confused while trying to understand the Processes and Threads concepts in Android. Below I mention a few questions. Maybe those are stupid questions, but please help me answer to answer these questions and clarify my doubts.
1) If I create a thread where will it run? in Main(UI) Thread?
2) If my created thread runs in the background as a worker Thread then what is the use of AsyncTask (I mean how it is better than thread)?
3)Can we create a Thread in AsyncTask?

1. If i create a thread where it will run? in Main(UI) thread/Worker Thread?
it will run in a Worker thread not in the Main Thread.
2.If my created thread runs on worker `Thread` then what is the use of `AsyncTask` (I mean how it is better than thread)?
AsyncTask is used to communicate with the Main Thread..For example you are dowloading File from internet so here you want to update the Download progress in Your Activity..for this AsyncTask better suits. You will update The Ui using onProgressUpdate() method.So you can easily communicate with UI thread.
3)Can we create a thread in Async task?
Yes you can create it but it is useless because AsyncTask has a doInBackGround()method that already runs in a different Thread so there is no need to create a new Thread inside AsyncTask.

If you are creating a thread in Activity. it will run as a separate thread. By default Activity runs in UI thread.It is also called main thread.
Async task is nothing but a worker thread which is used to run backround operations which will not block the UI thread. eg: downloading a file.
Asynctask itself a separte thread and it has its own life cycle.

1) It will run as a worker thread, not on the UI thread.
2) Async Task gives you the possibility to execute certain things before or after the task has finished. Especially useful when having to update UI values after getting data from an internet connection or similar actions. Also works great for progressdialogs.
It's a type of class (extends AsyncTask), so there's more structure to it then just starting a thread.
3) Yes, you can. Whether or not this would be very useful to you, is an entirely different question.

Related

where to use asynk task and why even it exist if Handler is there?

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.

Asynctask vs Thread in android

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.

Android Thread & AsyncTask

I have a code placed in the onActivityResult() but it is slowing my activity alot,
the code is to do Binarizng on Image.
I am confused whats to use AsyncTask or Thread,
can you help me with it
onActivityResult has nothing to do with threads or async tasks.
A thread allows your app to do two things at once. Doing so can be fairly risky (what if they write the same variables at the same time?). You need to be careful when using them.
An AsyncTask is a Thread that will automatically run some code on the main UI thread when its done. Its useful for running some code on a thread and then synchronizing results on the main thread.
onActivityResult is called when you are running a completely separate activity, either in your own app or in another person's. If you need to run another activity, this is the only way to get a result back from it. It has nothing to do with threads.
Use AsyncTask
AsyncTask Also uses Thread, but in a intelligent way. In android you can not update UI directly from a worker thread. But you can perform UI tasks from Asynctask. So this is a better option.
Both AsyncTask and Thread, let you run background task on a different thread.
But AsyncTask provide you various callback, so that you can Update UI once the background task is done Or Canceled.
So, if your task involve any UI update; please use AsyncTask.

Asynctask from non ui thread

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.

Android:: Blocking main thread for worker thread to finish before executing other tasks in main thread

I am executing some task in the UI thread and created a worker thread that does the networking stuff for me. However, I have something important that needs to be executed once the worker thread finishes. Could anybody please suggest me a solution?
{
Main thread...
worker thread created..and executed..
//I need to wait here for the worker thread to finish//
some useful task to be done
}
Thanks in advance!
You need to do things on the UI thread after worker has finished? Use runOnUiThread at the end of your worker or use AsyncTask with onPostExecute(). Blocking the UI thread while worker is running doesn't make any sense.
You don't. Blocking the UI thread violates the key rule of threading in Android.
Doing so can cause those annoying "Application not responding" dialogs, along with other problems.
From the Processes and Threads page of the developer docs:
So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. Thus, there are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
You should explore other solutions to what you need to accomplish. You need not give specifics on your problem, but ekholm's solution could work, as could simply calling a method in your Activity from the worker thread.

Categories

Resources