whats' the difference between Asynctask and thread in android? - android

I am currently developing an android app, there is always unexpected exception popup when I use AsyncTask or Thread. any one tell me what's the difference between them and how to use them ?

"there is always unexpected exception popup when I use AsyncTask or Thread."
It depends on how to use them, and your code inside it. Mostly when you are using Main UI Thread in this (other) thread or asynctask in-properly.
For difference between AsyncTask and Thread you have to search on SO and net. You can find easily it.
Anyway I recommended you to just go through this blog Android Thread Constructs(Part 4): Comparisons
And this SO question Difference between Service, Async Task & Thread?

You really need to read this properly.
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html

Mostly use AsyncTask - it's a dressed-up Thread that allows you to among other things interact with the GUI at the beginning, at the end and to report progress in a controlled manner. If you're really feeling like using a Thread, use IntentService instead.

its a very good question and must considered before start using one of them please go through this
Difference between Service, Async Task & Thread?

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, may be api level < 11), one instance of AsyncTask can be executed only once.

Related

Understanding when and why to use different Android threads

Hopefully someone can explain this to me or point me to a resource I can read to learn more. I am building an app that uses a ListView and a custom list adapter that I modeled off one of the many tutorials available online such as this one:
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
It worked fine. However, every example of how to do this runs the process of building the list of objects to be displayed and collecting the required data on separate threads.
I want to know why/couldn't you just put everything into onCreate? I can't see a reason why you would need separate threads to make this happen. Is there some general form/standard for when/what must me run on certain threads?
The Android docs on this are very good, as with most things.
The upshot is: the UI should always be responsive. So if you have some operation that will take enough time that the user will notice, you might want to consider not running it in the UI thread. Some common examples are network IO and database accesses. It's something of a case-by-case basis though, so you have to make the call for yourself a bit.
Well, if building the list of objects is not a relatively short process, doing it in onCreate() would be blocking/slowing the main thread. If you use a separate thread, it will allow the android os to load all of the UI elements while you are waiting for the list to be populated. Then when the list of objects is ready, you can instantly populate the already initialized UI, as opposed to waiting to initialize the UI until after the list of objects is built. It ensures that your application will always be responsive for the user.
Because you only have 0.5 sec to execute onCreate — after which the dreaded ADN (application not responding) error message is displayed. So unless your list view is super simple you won't make it it in time. And even if your list view is super simple it is better to learn it the proper way.
BTW: I don't even use threads, I use one or more Services to do all the work. Even more difficult to implement but more robust and responsive as well.
The reason you don't do things in onCreate or on the UI thread is for responsiveness. If your app takes too long to process, the user gets shown an App Not Responding dialog.
my teacher once said: every software can be written in a single (big) for loop.
And if you think: it can be... maybe at NDK level.
Some SDK developers wanted to make the software developers tasks easier and that's, why exists the SDK's and frameworks.
Unless you don't need anything from multitasking you should use single threading.
Sometimes there are time limitations, sometimes UI/background/networking limitations and need to do stuff in diff threads.
If you see source code of Asyntask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).
Why does it mean ? It means no magic in Asyntask or Handler. They just make your job easier as a developer.
For example: If ProgramA calls methodA(), methodA() would run in a different thread with ProgramA.You can easily test by:
Thread t = Thread.currentThread();
int id = t.getId();
And why you should use new thread ? You can google for it. Many many reasons.
So, what is the difference ?
AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.
What Handler and AsyncTask really help you with?
The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.
That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.
Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:
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 want to emphasize on two points:
1) Easy use of the UI thread (so, use when caller thread is UI Thread).
2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).
There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..
#: when you read Android document, you will see:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue
They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)

Android async Task Vs Native Java Threads [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Handler vs AsyncTask vs Thread
Am a newbie to android and am on the way developing my first app...
Which kind of threading is better to create process separate from UI thread?
AsyncTask or extending Thread class with Handler and Message?
I have gone throug this thread..
Put an object in Handler message
The person have told that, "Oh, and I'm moving away from using AsyncTask objects, as I believe they increase code coupling too much.".
What's meant by code coupling? Should I use Java thread with Handler and Message classes or should I use Async task?
As this is going to be your first app it would be best to put this question away for a while. Instead you would want to make your application working anyhow. Doing that you will gain enough experience to decide for yourself.
Having said this AsyncTask seems to be easier to use if what you need is to do something in background and present progress and results in UI.
One real problem with either approach is that when you rotate your device your UI gets recreated. And if you store ane references to the older UI in your thread/asynctask and use them your app the crashes.
AsyncTask uses Java's native threads in the background. The advantage of using them is that you get 3 methods - onPreExecute, doInBackground & onPostExecute which make you life easier.
AsyncTask is a nice abstraction for well-defined tasks that need to be done on a worker thread (to avoid blocking the main thread), while reporting progress and publishing results to the UI. Examples of such tasks are : downloading file from internet, calling a webservice, querying the database etc. It maintains a pool a worker threads to run these tasks. Using AsyncTask frees you from having to write code to create and mange threads and to dispatch UI updates to the UI thread.
AsyncTask is not appropriate when the background task is an ongoing process rather than a well-defined task. Examples : playing music, continuously tracking location, continuously downloading news feeds etc. In such cases, it is appropriate to create and manage a separate thread.

Real difference between AsyncTask and Thread

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.

Handler vs Thread

I would like to know, once for all. I've read in many places. When I want do some 'long time operations' I should use a Handler.
But I don't get why? All my 'long-time-operations' I surround with a regular threads, and it works fine.
Why would I use Handler for this?
The only time I had to use Handler was, when I had to schedule some task(postDelayed)
Is there any main idea I miss about handlers(When I should really use it)? Or maybe there isn't really difference?
A Handler lets you communicate back with the UI thread from your background thread. This is because UI operations are forbidden from within background threads. Note that starting at version 1.5, the AsyncTask class makes it much easier to do so.
It can't just be about getting you back to the UI thread since runOnUiThread(Runnable) does that very nicely. I suspect this is more about making it easier for Android to manage threads and other resources that shouldn't live outside of an Activity's context, and that the "Activity has leaked..." exceptions tell you when that's happened.

Handler vs AsyncTask

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.

Categories

Resources