Книга: Beginning Android
Tying Up Loose Threads
Tying Up Loose Threads
A common pattern in Android is to perform some work on a background thread, then update something on the UI thread when the background work is complete. A simple way to handle this is to fork a background thread and use a Handler
or runOnUiThread()
to accomplish the UI thread work. However, the danger here is in forking too many threads — the user might do something that causes you to fork many threads in short order, bogging down the device at best. And while there are classes that can help you manage a work pool (e.g., LinkedBlockingQueue
), their use can be mildly tedious.
Enter AsyncTask
.
AsyncTask
manages a work queue with a thread pool, so you do not need to implement that yourself. Moreover, all of the communication between foreground and background threads are handled for you. All you need to do is override a few methods to describe what you want done in the background or in the foreground.
To create an AsyncTask
, simply extend one anonymously, like you might do to create a Runnable
. You can then override whatever methods you need to for the pattern you want:
• Override onPreExecute()
to specify something that should be done on the UI thread when the task is started
• Override doInBackground()
to indicate the work that should be done in the background thread
• Override onProgressUpdate()
to update your progress on the UI thread when doInBackground()
calls publishProgress()
(e.g., update a ProgressBar
)
• Override onPostExecute()
to do whatever work needs to be done on the UI thread after the background work is complete
Using your custom AsyncTask
is then a matter of calling execute()
on one of its instances, such as one might call run()
on a Runnable
.
- 4 A few ways to use threads
- 4.1. THREADS
- 4.1.1. Introduction to Threads
- 4.1.3. Design Issues for Threads Packages
- 4.1.4. Implementing a Threads Package
- 7.3.2. Threads
- 8.2.2. Threads
- 9.2.2. Threads
- 10.2. THREADS
- 10.2.1. Introduction to DCE Threads
- Emptying the print queue
- Passing Parameters to Threads