标签:java android asynctask 异步 android asynctask
异步任务AsyncTask
AsyncTask主要用来更新UI线程,比较耗时的操作可以在AsyncTask中使用。
AsyncTask是个抽象类,使用时需要继承这个类,然后调用execute()方法。注意继承时需要设定三个泛型Params,Progress和Result的类型,如AsyncTask<Void,Inetger,Void>:

package com.example.asynctestdemo;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button bt_execute;
private Button bt_cancel;
private ProgressBar progressBar;
private TextView textView;
MyTask myTask;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_execute = (Button) findViewById(R.id.bt_execute);
bt_cancel = (Button) findViewById(R.id.bt_cancel);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
textView = (TextView) findViewById(R.id.text_view);
bt_execute.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 实例化异步任务MyTask类
myTask = new MyTask();
myTask.execute("http://www.baidu.com");
}
});
bt_cancel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myTask.cancel(true);
}
});
}
class MyTask extends AsyncTask<String, Integer, String> {
// onpreExecute()方法用于,在执行后台任务前,做一些UI操作
protected void onPreExecute() {
textView.setText("Loading......");
}
// doInBackground()方法,内部执行后台耗时任务操作,但不是不能在此方法内修改UI
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
long total = entity.getContentLength();
System.out.println(total);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int count = 0;
int length = -1;
while ((length = is.read(buf)) != -1) {
baos.write(buf, 0, length);
count+=length;
// 调用publishProgress()方法公布进度,最后onProgressUpdata方法将被执行
publishProgress((int) (count/length));
//为了更明显的展现效果,每次暂停0.5s
Thread.sleep(500);
}
return new String(baos.toByteArray(), "utf-8");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
// onProgressUpdata方法,用于更新进度信息,例如执行进度条程序
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
textView.setText("Loading......" + values[0]);
}
// onPostExecute方法,用于在执行完后台任务后,更新UI,显示结果
protected void onPostExecute(String result) {
textView.setText(result);
}
// onCacelled方法,用于在取消执行中的任务时,更改UI
protected void onCancelled() {
textView.setText("cancelled");
progressBar.setProgress(0);
}
}
}标签:java android asynctask 异步 android asynctask
原文地址:http://blog.csdn.net/itwuchen/article/details/41876965