异步task是一个线程,但是可以和ui主线程交互。
他可以传入参数,参数传入doInBackground(Integer... params)。doInBackground(Integer... params)的返回值作为result,传递给onPostExecute作为参数。doInBackground(Integer... params)方法中调用了 publishProgress(p)方法,在此方法调用后就会直接触发 protected void onProgressUpdate(Integer... progress),p作为参数传递给progress。
实例:
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class AsyncTaskTest extends Activity {
TextView tv;
final String TAG="AsyncTaskTest";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
new MyTask().execute(6, 12, 7);
}
class MyTask extends AsyncTask<Integer, Integer, Integer> {
//此方法是在调用doInBackground之前调用的,主要做一些准备工作,例如打开一个进度调对话框。
@Override
protected void onPreExecute() {
super.onPreExecute();
tv.setText("test");
Log.e(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AsyncTaskTest", "onPreExecute()");
}
//这里是要在后台线程中做的事情,只要这一个方法是后台线程的,其余的方法都是操作前台的,所有的操作 都用于前台。
@Override
protected Integer doInBackground(Integer... params) {
Log.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AsyncTaskTest", "doInBackground()");
int p = 0;
for (int index = 0; index < params.length; index++) {
int num = params[index];
for (int j = 0; j < num; j++) {
if (num - j <= 0) {
break;
}
p++;
publishProgress(p);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return p;
}
@Override
protected void onProgressUpdate(Integer... progress) {
Log.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AsyncTaskTest", "onProgressUpdate()");
tv.append("\nProgress: " + progress[0]);
}
//doInBackground的return值是传入的result,是在doInBackground做完后执行的操作。
@Override
protected void onPostExecute(Integer result) {
Log.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AsyncTaskTest", "onPostExecute()");
tv.append("\nFinished. Result: " + result);
}
@Override
protected void onCancelled() {
super.onCancelled();
Log.d(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>AsyncTaskTest", "onCancelled()");
}
}
}