/**
AsyncTask 可以判断的三种状态
AsyncTask.Status FINISHED Indicates that onPostExecute(Result) has finished.
AsyncTask.Status PENDING Indicates that the task has not been executed yet.
AsyncTask.Status RUNNING Indicates that the task is running.
*/
public class MyActivity extends Activity {
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
//在主线程中做准备工作
protected void onPreExecute() {
}
//线程中运行
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));//启动onProgressUpdate方法
// Escape early if cancel() is called
// 如果被取消可以更早的结束
if (isCancelled()) break;
}
return totalSize;
}
//在主线程中运行
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
//在主线程中返回结果
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
//如果调用cancel方法后不会调用onPostExecute,直接调用onCancelled
protected void onCancelled() {
}
}
private AsyncTask<URL, Integer, Long> mLoginTask;
protected void onCreate(Bundle savedInstanceState) {
mLoginTask = (DownloadFilesTask) getLastNonConfigurationInstance();//读取先前保存的引用
if (mLoginTask != null && mLoginTask.isCancelled()) {
//如果cancel成功就重新开始
if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again.");
mLoginTask = new LoginTask().execute();
}
}
public Object onRetainNonConfigurationInstance() {
if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()");
if (mLoginTask != null) {
mLoginTask.cancel(true);//在线程运行中不能立即cancel,参数true表示线程应该被中断
}
return mLoginTask;
}
}