Am a noob learning Android via a book and for threading I see there are 3 main ways that are explained in the book:
- Handlers via messaging
- Handlers via post
- Asynctask
All 3 seem good, my question is:
Is there a specific time when you use one of the above? Or is it personal preference?
EDIT:
If its not personal preference, please give me an example as to when you would use one if not the other (even a link would be appreciated)
Because I am planning on having multiple threads running (eg, one for total app running time, one for time before answer is selected etc in the app, one for moving the background image etc) and want to know which to choose. I can do the functionality of what I want using either of these 3 methods so am confused as to why there are 3 when it can be done with either one.
Thanks!
Handler is a very basic way that allows you to execute some code on a different thread, typically UI thread. It does not tell you how to run your threads and you are free to do whatever you want in that respect. I would choose
handleMessageapproach if you have explicit messaging. That is you need to have some data sent and received. If you just need to do something, you can useRunnable. However, both methods are usable and a choice often would be result of a preference.AsyncTaskis higher level concept that uses handlers under the hood. If you use it, you will not have to deal with threads yourself. Your asynchronous code will be executed via thread pool and controlled by the framework. You will have two methods that allow you to execute code on UI thread (onPostExecuteandonProgressUpdate).In a nutshell, choose
AsyncTaskfor most things that you do with multiple threads it will absolve you of a need to deal with thread management yourself. If you must have your own threads only then use handlers. Note however, that there are other cases when you have to use handlers. For example, withMessenger. Also I had cases when usingonProgressUpdateis not sufficient. In this case I would use handler as well fromdoInBackground.