主要是以一个下载网页为例,要求能够实时的显示进度
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
/>
<Button
android:id="@+id/executeBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始获取"/>
<Button
android:id="@+id/cancelBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取消"
android:enabled="false"/>
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progress="0"
android:max="100"
style="@android:style/Widget.ProgressBar.Horizontal"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txtContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
通过AsnycTask实现的
package com.lei.AsynctaskDemo;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class MyActivity extends Activity {
private TextView resultView = null;
private ProgressBar progressBar= null;
private Button executeBtn = null;
private Button cancelBtn = null;
private MyTask myTask = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
public void initView(){
resultView = (TextView)findViewById(R.id.txtContent);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
executeBtn = (Button)findViewById(R.id.executeBtn);
cancelBtn = (Button)findViewById(R.id.cancelBtn);
executeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myTask = new MyTask();
myTask.execute("http://www.renren.com");
executeBtn.setEnabled(false);
cancelBtn.setEnabled(true);
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myTask.cancel(true);
executeBtn.setEnabled(true);
cancelBtn.setEnabled(false);
}
});
}
/**
* public abstract class AsyncTask<Params, Progress, Result> {
* 三种泛型类型分别代表“启动任务执行的输入参数”、
* “后台任务执行的进度”、“后台计算结果的类型”。
* 在特定场合下,并不是所有类型都被使用,如果没有被使用,
* 可以用java.lang.Void类型代替。
*/
class MyTask extends AsyncTask<String,Integer,Object>{
@Override
protected Object doInBackground(String... params) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(params[0]);
HttpResponse response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
long totalLength = entity.getContentLength();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte []buffer = new byte[1024];
int length = 0;
int count = 0;
while((length=inputStream.read(buffer))!=-1){
baos.write(buffer,0,length);
count +=length;
//调用publishProgress公布进度,最后onProgressUpdate方法将被执行
publishProgress((int) ((count / (float) totalLength) * 100));
Thread.sleep(500);//方便演示进度
}
return baos.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute() {
Log.d("renlei","onPreExecute");
resultView.setText("loading.....");
}
//onPostExecute方法用于在执行完后台任务后更新UI,显示结果
@Override
protected void onPostExecute(Object o) {
Log.d("renlei","onPostExecute");
executeBtn.setEnabled(true);
cancelBtn.setEnabled(false);
resultView.setText(o.toString());
}
//onProgressUpdate方法用于更新进度信息
@Override
protected void onProgressUpdate(Integer... values) {
Log.d("renlei","onProgressUpdate"+values[0]);
progressBar.setProgress(values[0]);
resultView.setText("loading..."+values[0]+"%");
}
@Override
protected void onCancelled() {
Log.d("renlei", "onCancelled");
resultView.setText("canceled");
progressBar.setProgress(0);
executeBtn.setEnabled(true);
cancelBtn.setEnabled(false);
}
}
}
通过Handler加Thread实现
package com.lei.AsynctaskDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
/**
* User: renlei
* Date: 14-9-24
* Time: 下午3:27
* Email:lei.ren@renren-inc.com
*/
public class MyActivity2 extends Activity {
private TextView resultView = null;
private ProgressBar progressBar = null;
private Button executeBtn = null;
private Button cancelBtn = null;
private Handler mHandler = null;
private Thread t = null;
private boolean tIsStop = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
public void initView() {
resultView = (TextView) findViewById(R.id.txtContent);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
executeBtn = (Button) findViewById(R.id.executeBtn);
cancelBtn = (Button) findViewById(R.id.cancelBtn);
executeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
executeBtn.setEnabled(false);
cancelBtn.setEnabled(true);
t = new MyThread();
tIsStop = false;
t.start();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.arg1 < 100) {
progressBar.setProgress(msg.arg1);
resultView.setText("loading..." + msg.arg1 + "%");
}
if (msg.arg1 == 100) {
progressBar.setProgress(msg.arg1);
resultView.setText(msg.obj.toString());
executeBtn.setEnabled(true);
cancelBtn.setEnabled(false);
}
}
};
}
});
cancelBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
executeBtn.setEnabled(true);
cancelBtn.setEnabled(false);
stopThread();
progressBar.setProgress(0);
resultView.setText("canceled");
}
});
}
public void stopThread(){
tIsStop = true;
Log.d("renlei","线程已经被终止");
}
class MyThread extends Thread {
@Override
public void run() {
Looper.prepare();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.renren.com");
HttpResponse response = httpClient.execute(httpGet);
Message msg = null;
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
long totalLength = entity.getContentLength();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
int count = 0;
while ((length = inputStream.read(buffer)) != -1&&!tIsStop) {
baos.write(buffer, 0, length);
count += length;
msg = mHandler.obtainMessage();
msg.arg1 = (int) ((count / (float) totalLength) * 100);
msg.obj = baos.toString();
mHandler.sendMessage(msg);
Log.d("renlei","loading"+msg.arg1);
Thread.sleep(500);//方便演示进度
}
}
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
}
}
}
注意别忘了加网络权限