For the More Curious: AsyncTasks vs Threads

Now that you understand Handler and Looper, AsyncTask may not seem quite so magical. It is still less work than what you have done here. So why not use AsyncTask instead of a HandlerThread?

There are a few reasons. The most fundamental one is that AsyncTask is not designed for it. It is intended for work that is short-lived and not repeated too often. Your code in the previous chapter is a place where AsyncTask shines. But if you are creating a lot of AsyncTasks or having them run for a long time, you are probably using the wrong class.

A more compelling technical reason is that in Android 3.2, AsyncTask changed its implementation in a significant way. Starting with Android 3.2, AsyncTask does not create a thread for each instance of AsyncTask. Instead, it uses something called an Executor to run background work for all AsyncTasks on a single background thread. That means that AsyncTasks will run one after the other. A long-running AsyncTask will hog the thread, preventing other AsyncTasks from getting any CPU time.

It is possible to safely run AsyncTasks in parallel by using a thread pool executor instead, but we do not recommend doing so. If you are considering doing this, it is usually better to do your own threading, using Handlers to communicate back to the main thread when necessary.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.178.37