package com.sean.demo.asynctask;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class AsyncTaskDemoActivity extends Activity {
private static final String TAG = "INFO";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyAsyncTask task = new MyAsyncTask(this);
task.execute("Message");
}
class MyAsyncTask extends AsyncTask<String, Integer, String>{
//An asynchronous task is defined by 3 generic types, called Params, Progress and Result
//进度框
ProgressDialog pdialog;
public MyAsyncTask(Context context) {
// 构造函数
pdialog = new ProgressDialog(context, 0);
pdialog.setMax(100);
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdialog.show();
}
@Override
protected String doInBackground(String... params) {
// 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。
// 这里将主要负责执行那些很耗时的后台计算工作。
// 可以调用 publishProgress方法来更新实时的任务进度。
// 该方法是抽象方法,子类必须实现。
Log.i(TAG,"doInBackground");
try {
Log.i(TAG,params[0]);
//进度条控制
for(int count=0;count<100;count++){
publishProgress((int) ((count / (float)100) * 100));
Thread.sleep(10);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return params[0]+" result"; //返回处理完成的结果。
}
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
// 在doInBackground 执行完成后,onPostExecute 方法将被UI thread调用,
// 后台的计算结果将通过该方法传递到UI thread.
super.onPostExecute(result);
pdialog.dismiss();
Log.i(TAG,"onPostExecute");
Log.i(TAG,result); //这里显示的是Message result
}
@Override
protected void onPreExecute() {
// 在执行doInBackground前被主线程调用。
super.onPreExecute();
Log.i(TAG,"onPreExecute");
}
@Override
protected void onProgressUpdate(Integer... values) {
// 在publishProgress方法被调用后,
// UI thread将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
super.onProgressUpdate(values);
pdialog.setProgress(values[0]);
}
}
}
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
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
.