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 类,它允许在后台线程上执行任务,从而不会中断主线程。要使用 AsyncTask,你应该定义它的子类,就像我们对 FetchWeatherTask 所做的那样。有四个重要的方法会被重载:
- onPreExecute - 在任务启动前,此方法在 UI 上运行,并且负责任何需要完成的设置。
- doInBackground - 这是你要脱离主线程完成的实际任务的代码。它将在后台线程上运行,并且不会中断 UI。
- onProgressUpdate - 此方法在 UI 线程上运行,并且用于显示任务的进度(例如显示加载条动画)。
- onPostExecute - 在任务完成之后,此方法在 UI 上运行。
请注意,在启动 AsyncTask 后,它会关联到启动它的 Activity 。在 Activity 被销毁时(例如旋转手机时),你启动的 AsyncTask 将引用被销毁的 Activity 而不是新创建的 Activity。这就是 AsyncTask 用于长时间运行的任务很危险的原因之一。
AsyncTaskLoader
启动
getSupportLoaderManager().initLoader(FORECAST_LOADER_ID, bundleForLoader, callback);
刷新
getSupportLoaderManager().restartLoader(FORECAST_LOADER_ID, bundleForLoader, this);
缓存结果
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);
}
};