I have been reading Android documentation (AsyncTask, Thread) and vogella tutorial about this matter, but I have doubts yet.
For example, I want to send a message from an Android app to a server. And I would like this process to be responsive. What should I use?
I have seen examples where they create a new Thread for not block UI, but this way we don't have the progress of process, also you have to process the response within the Thread because the run() method doesn't returning anything.
AsyncTask seems better option than Thread, but I don't know what are the consequences of using an AsyncTask instead of a Thread.
Please read this blog
http://crazyaboutandroid.blogspot.in/2011/12/difference-between-android.html
and Details are:
Difference between Android Service,Thread,IntentService and AsyncTask
When to use ?
Service
Task with no UI, but shouldn't be too long. Use threads within service for long tasks.
Thread
- Long task in general.
- For tasks in parallel use Multiple threads (traditional mechanisms)
AsyncTask
- Small task having to communicate with main thread.
- For tasks in parallel use multiple instances OR Executor
All other answers here are not complete, there is a big difference between AsyncTask and Thread, i.e.
Thread can be triggered from any thread, main(UI) or background; but AsyncTask must be triggered from main thread.
Also on lower API of Android(not sure, maybe API level < 11), one instance of AsyncTask can be executed only once.
For more information read Difference between Android Service, Thread, IntentService and AsyncTask
In general
Thread
Long task in general.
For tasks in parallel use Multiple threads (traditional mechanisms)
AsyncTask
Small task having to communicate with main thread.
For tasks in parallel use multiple instances OR Executor
in general using of 2 this features are equivalent, but AsyncTask is more simple in terms of integration with GUI
I would prefer to Use Async Task as it will let you know when the
background process gets started and over and when can I parse
the response.
Async has methods like onPreExecute and onPostExecute which will allow us to do tasks before and after calling the background
tasks.
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 control its own functions
doInBackground(Params... params),
onCancelled(),
onPostExecute(Result result),
onPreExecute(),
nProgressUpdate(Progress... values),
publishProgress(Progress... values)
AsyncTask enables proper and easy use of the UI thread. - from Developer.
The thing is - AsyncTask is a special kind of Thread - one which is a GUI thread, it works in the background and also let's you do something with the GUI - it is basically "pre-programmed" for you with functions onPreExecute(), do inBackground(), onPostExecute().
In order to make Thread work that way, you have to write a loooot of code.
Related
I was wondering is it ok to execute a Thread inside the doInBackground method of Asynctask. Should I avoid using this kind of structure on my codes? And if yes, why should I avoid it? Would this cause any ineffectiveness in my apps?
In principle, there's no problem with starting a thread in the doInBackground() of an AsyncTask, but sometimes you see this done not because it's the right thing to do, but because of a misunderstanding about how AsyncTask works.
The point is that doInBackground() will automatically get executed on a background (non-GUI) thread, without you needing to create a thread for it yourself. That, in fact, is the whole point of an AsyncTask. So if you have a simple, linear task that you want executed in the background, you do it with an AsyncTask, and you don't need to do any manual thread creation.
Where you might want to start a new thread in an AsyncTask is if you want your background task to use multiple threads to complete. Suppose that you were writing an app to check the online status of various servers, and display something about their status on the screen. You'd use an AsyncTask to do the network access in the background; but if you did it in a naive way, you'd end up with the servers being pinged one by one, which would be rather slow (especially if one was down, and you needed to wait for a timeout). The better option would be to make sure that each server was dealt with on its own background thread. You'd then have a few options, each of which would be defensible:
Have a separate AsyncTask for each server.
Create a thread for each server inside the doInBackground() of your single AsyncTask, and then make sure that doInBackground() doesn't complete until all the individual threads have completed (use Thread.join()).
Use a ThreadPool / some kind of ExecutorService / a fork/join structure inside your single AsyncTask, to manage the threads for you.
I would say that with modern libraries there is rarely a need for manual thread creation. Library functions will manage all of this for you, and take some of the tedium out of it, and make it less error-prone. The third option above is functionally equivalent to the second, but just uses more of the high-level machinery that you've been given, rather than going DIY with your thread creation.
I'm not saying that threads should never be created manually, but whenever you're tempted to create one, it's well worth asking whether there's a high-level option that will do it for you more easily and more safely.
is it ok to execute a Thread inside the doInBackground method of
Asynctask.
yes it is but it really depends on your application and your usage. for example in a multithread server-client app you must create for each incoming clients one thread and also you must listen on another thread. so creating thread inside another is ok. and you can use asynctask for listening to your clients.
Should I avoid using this kind of structure on my codes? And if yes,
why should I avoid it?
If you design it carefully you do not need to avoid, for example make sure that on rotation you do not create another asynctask because for example if your user rotates 5 times you create 5 asynctasks and in each of them you create a thread that means you will get 10 threads, soon you will get memory leak.
Would this cause any ineffectiveness in my apps? Can you explain
these questions please.
I answered it above, I think better idea is using Thread Pool to minimize number of creating your threads or wraping your asynctask in a UI less fragment so you are sure you have one asynctask regardless of whats going to happen.
In any higher programming language, there is concept of multi-tasking. Basically the user needs to run some portion of code without user interaction. A thread is generally developed for that. But in Android, multi-tasking can be done by any of the three methods Thread and AsyncTask.
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:
1. onPreExecute()
Invoked on the UI thread before the task is executed
2. doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
3. onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
4. onPostExecute(Result)
Invoked on the UI thread after the background computation finishes.
And there are lot of good resources over internet which may help you:
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html http://www.mergeconflict.net/2012/05/java-threads-vs-android-asynctask-which.html
I would say there is no problem in doing that if you need something to run concurrently beside the AsyncTask.
One issue could be one of readability (using 2 different ways for concurrency), but I really can't see the harm in that - especially if one of the tasks needs to show it's result in the UI and the other one doesn't.
I have a block of code
list = geocoder.getFromLocation(
locationNetwork.getLatitude(),
locationNetwork.getLongitude(), 3);
where i am trying to retrieve the last location via getFromLocation(LocationManager). Since that can take time i want to put it on a different thread than the UI. But i am confused what should be used. Should a handler or Async task be used for this purpose. I am confused as when an handler and Async task should be used in Android. Can any one explain me with some example,scenarios..
Thanks.!
I think you're getting mixed up here. Handlers and an Async task are two different things. A handler is used to communicate between threads, see here, while an Async task is basically an easier to use thread in Android. If you create a new thread and want to communicate with another thread, you have to use a Handler. However, Google made it easier by providing the Async task class which allows communication with the main UI thread without the use of handlers, see here. So in short, use an Async task for your purpose. The link I have provided actually provides an example usage and goes into depth about Asyncs. If you need clarification let me know.
See this SO answer it talks about the difference of AsyncTask, Handler, and Thread
Most of the time it is developer preference, if you are talking about creating a Thread. If you need to update the UI, especially while the background Thread is running, then I think AsyncTask is easier. Both of them allow you to continue working with the UI while they do the heavier lifting in the background.
You can use an AsyncTask and do the work in doInBackground() then update the UI on any of the other AsyncTask methods. If you might want to use this Thread in more than one place then make it a separate file and you can pass Activity Context to it through its constructor if you need it. If you will only use it in one Activity then you can make it an inner class of your Activity then it will have access to all member variables of that Activity
I have question which puzzles me.
Imagine I wanna do something in another thread, like fetching GPS/Location stuff, which as recommended in the SDK documents, must use a background thread.
So here is the question: What's the difference between
Creating a Thread in background via AsyncTask AND
Creating Thread thread1 = new Thread(new Runnable() ... and implementing run()?
AsyncTask is a convenience class for doing some work on a new thread and use the results on the thread from which it got called (usually the UI thread) when finished. It's just a wrapper which uses a couple of runnables but handles all the intricacies of creating the thread and handling messaging between the threads.
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.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need 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.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
The Runnable interface is at the core of Java threading. The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
Also if I quote from this blog:
if you need SIMPLE coding use AsyncTask and if you need SPEED use traditional java Thread.
Key differences:
AsyncTask is an asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. It can't be done with normal thread unless you use Handler on UI Thread and post a message OR directly change attribute of an object by implementing proper synchronization.
As recommended by developer guide regarding Thread performance,
There are a few important performance aspects to keep in mind. First, by default, an app pushes all of the AsyncTask objects it creates into a single thread. Therefore, they execute in serial fashion, and—as with the main thread—an especially long work packet can block the queue. For this reason, we suggest that you only use AsyncTask to handle work items shorter than 5ms in duration..
But normal Thread can be used for long running tasks.
Plain java Threads are not much useful for Android unlike HandlerThread, which has been provided by Android framework.
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that start() must still be called.
Refer to below post to know more details:
Handler vs AsyncTask vs Thread
Also take in count that starting on Android v4.04, you can't have more than one AsyncTasks at a time, unless you lose compatibility with lower versions. Be aware!
AsyncTask deprecated with api level 30. Using thread/runnable is convenient
One obvious drawback for AsyncTask class is that after Android 3.0 asynctasks are executed according to the sequence of the start time. that is tasks are executed one by one, unless you execute the task by calling 'executeOnExecutor(Executors.newCachedThreadPool())'. this method would create your own thread pool.
Better to use the new Job Scheduler in the support library.
I'm using multiple lists embedded one inside another. This obviously slows down the App, thus I thought of using multi-threading. Treating separate lists as threads, and then the data loaded inside them as separate threads to make it faster.
Is this a better way to do it? Can I've certain examples based on it? Or even links?
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
It is better to use an async task to load a listview so you dont block the main UI
Your question title does not match the question body, you'll get better responses if you change them to relate better.
See the following question for an explaination of the differences: How to know when to use an async task or Handler
That said, in your case, you want to parralelize the population of the listboxes as opposed to the handling of messages, so AsyncTask makes most sense.
Handler and AsyncTasks are way to implement multithreading with UI/Event Thread.
Handler can be created from any thread and it runs on the thread which created it.
It handles and schedules messages and runnables sent from background to the thread which created it
.
We should consider using handler it we want to post delayed messages or send messages to the MessageQueue in a specific order.
AsyncTask is always Triggered or created from main thread.
Its methods onPreExecute(),onPostExecute(),onProgressUpdate() runs on main thread(or UI thread) and doInBackground() runs on worker thread(or background thread).AsyncTask enables proper and easy use of the UI thread.
This class allows to perform background operations and publish results on the UI thread .
We should consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.
I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?
IMO, 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.
However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.
My rule of thumb would be:
If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
Always try to avoid using AsyncTask when possible mainly for the following reasons:
AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed
AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it
AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.
In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground.
Read this thread for more insights on this problems:
Is AsyncTask really conceptually flawed or am I just missing something?
To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.
If you want to do a calculation every x seconds, you should probably schedule a Runnable on a Handler (with postDelayed()) and that Runnable should start in the current UI thread. If you want to start it in another thread, use HandlerThread.
AsyncTask is easier to use for us but no better than handler.
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.
You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.
AsyncTask presumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once (after this, its status is FINISHED and you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTOR for a parallel execution, but the effort might be not worthy.
Handler doesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.
Check different kind of Handler examples here.
They are best interview question which is asked.
AsyncTask - They are used to offload of UI thread and do tasks in background.
Handlers - Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.
So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.
doInBackground - basically does work in another thread.
onPostExecute - posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.
So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.