Книга: 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.

Оглавление книги

Оглавление статьи/книги

Генерация: 1.228. Запросов К БД/Cache: 3 / 1
Вверх Вниз