您的位置:首页 > 移动开发 > Android开发

Android异步任务AsyncTask实现方式

2012-10-07 20:13 543 查看
在Android编程中,异步操作是必须掌握的基本知识。在Android中UI线程响应不能超过5s,否则会出现ANR,因此我们常常将耗时操作放在非工作线程中执行。AsyncTask是Android推荐实现异步操作的方式,希望大家熟练掌握。

首先,我们实现异步操作需要继承AsyncTask类,并定义三个返回类型(没有返回类型使用void),具体代码如下所示:

class UpdateTextTask extends AsyncTask<Void, Integer, Integer>

通过打印回调方法的Log日志,三个参数类型依次代表:

第一个Void参数类型代表doInBackground(Void... params)回调方法的参数类型

第二个Integer 参数类型代表onProgressUpdate(Integer... values)的参数类型,该方法在UI线程中执行。

第三个Integer参数类型代表doInBackground的返回值和onPostExecute(Integer integer)(该方法在UI线程中执行)方法的参数类型

实例代码如下:

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyActivity extends Activity {
private Button btn;
private TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.start_btn);
tv = (TextView) findViewById(R.id.content);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
update();
}
});
}

private void update() {
UpdateTextTask updateTextTask = new UpdateTextTask(this);
updateTextTask.execute();
}

class UpdateTextTask extends AsyncTask<Void, Integer, Integer> {
private Context context;

UpdateTextTask(Context context) {
this.context = context;
}

/**
* 运行在UI线程中,在调用doInBackground()之前执行
*/
@Override
protected void onPreExecute() {
Toast.makeText(context, "开始执行", Toast.LENGTH_SHORT).show();
}

/**
* 后台运行的方法,可以运行非UI线程,可以执行耗时的方法
*/
@Override
protected Integer doInBackground(Void... params) {
int i = 0;
while (i < 10) {
i++;
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
return null;
}

/**
* 运行在ui线程中,在doInBackground()执行完毕后执行
*/
@Override
protected void onPostExecute(Integer integer) {
Toast.makeText(context, "执行完毕", Toast.LENGTH_SHORT).show();
}

/**
* 在publishProgress()被调用以后执行,publishProgress()用于更新进度
*/
@Override
protected void onProgressUpdate(Integer... values) {
System.out.println("do onProgressUpdate.........");
tv.setText("" + values[0]);
}
}
}

AsyncTask异步任务的时序图如图1-1所示:



图1-1AsyncTask异步加载时序图

说明:AsyncTask对象执行excute()方法后,内部方法执行的顺序:

执行onPreExecute(),该方法在UI线程中执行;
执行doInBackground(),该方法并不在UI线程中,因此不能对UI控件进行设置和修改;
执行publishProgress(i),每次调用都会触发onProgressUpdate()方法,该方法的参数值会赋值给onProgressUpdate的参数;
在doInBackground()执行完成后,调用onpostExecute()方法。 doInBackground()的返回值,传递给onpostExecute()方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: