Android Thread & AsyncTask - android

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.

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.

Thread ,UI thread, Worker Thread, Async Task

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.

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.

Which is better to work upon among Async Task, Runnable and Handler in Android

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.

Difference between Service, Async Task & 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.

Categories

Resources