AsyncTask
http://developer.android.youdaxue.com/reference/android/os/AsyncTask.html
public abstract class AsyncTask extends [Object](http://developer.android.youdaxue.com/reference/java/lang/Object.html)
[java.lang.Object](http://developer.android.youdaxue.com/reference/java/lang/Object.html)
android.os.AsyncTask<Params, Progress, Result>
AsyncTask enables proper and easy use of the UI thread. This class allows you to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
AsyncTask 是易于使用的 Android 類它呀,它允許在后臺(tái)線程上執(zhí)行任務(wù),從而不會(huì)中斷主線程淋淀。要使用 AsyncTask袒炉,你應(yīng)該定義它的子類刃泡,就像我們對(duì) FetchWeatherTask 所做的那樣。有四個(gè)重要的方法會(huì)被重載:
- onPreExecute - 在任務(wù)啟動(dòng)前,此方法在 UI 上運(yùn)行渡紫,并且負(fù)責(zé)任何需要完成的設(shè)置端蛆。
- doInBackground - 這是你要脫離主線程完成的實(shí)際任務(wù)的代碼凤粗。它將在后臺(tái)線程上運(yùn)行,并且不會(huì)中斷 UI今豆。
- onProgressUpdate - 此方法在 UI 線程上運(yùn)行嫌拣,并且用于顯示任務(wù)的進(jìn)度(例如顯示加載條動(dòng)畫)。
- onPostExecute - 在任務(wù)完成之后呆躲,此方法在 UI 上運(yùn)行异逐。
請(qǐng)注意,在啟動(dòng) AsyncTask 后插掂,它會(huì)關(guān)聯(lián)到啟動(dòng)它的 Activity 灰瞻。在 Activity 被銷毀時(shí)(例如旋轉(zhuǎn)手機(jī)時(shí)),你啟動(dòng)的 AsyncTask 將引用被銷毀的 Activity 而不是新創(chuàng)建的 Activity辅甥。這就是 AsyncTask 用于長(zhǎng)時(shí)間運(yùn)行的任務(wù)很危險(xiǎn)的原因之一箩祥。
AsyncTaskLoader
啟動(dòng)
getSupportLoaderManager().initLoader(FORECAST_LOADER_ID, bundleForLoader, callback);
刷新
getSupportLoaderManager().restartLoader(FORECAST_LOADER_ID, bundleForLoader, this);
緩存結(jié)果
return new AsyncTaskLoader<String[]>(this) {
/* This String array will hold and help cache our weather data */
String[] mWeatherData = null;
// COMPLETED (3) Cache the weather data in a member variable and deliver it in onStartLoading.
/**
* Subclasses of AsyncTaskLoader must implement this to take care of loading their data.
*/
@Override
protected void onStartLoading() {
if (mWeatherData != null) {
deliverResult(mWeatherData);
} else {
mLoadingIndicator.setVisibility(View.VISIBLE);
forceLoad();
}
}
...
...
...
/**
* Sends the result of the load to the registered listener.
*
* @param data The result of the load
*/
public void deliverResult(String[] data) {
mWeatherData = data;
super.deliverResult(data);
}
};