Android:AsyncTask 使用
Task 的实例必须在 UI thread 中创建
execute 方法必须在 UI thread 中调用
不要手动的调用 onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法
该 task 只能被执行一次,否则多次调用时将会出现异常
一个简单进度条的例子:
<?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">
<ProgressBar android:id="@+id/progress_bar"
android:layout_width="200dip" android
:layout_height="10dip"
android:layout_gravity="center"
android:max="100" style="?android:attr/progressBarStyleHorizontal"
android:progress="0">
</ProgressBar>
</LinearLayout>
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ProgressBar;
public class Double extends Activity {
public ProgressBar pBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pBar = (ProgressBar) findViewById(R.id.progress_bar);
//AsyncTask.execute()要在主线程里调用
new AsyncLoader().execute((Void)null);
}
public void initProgress() {
pBar.setProgress(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pBar.setProgress(50);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
pBar.setProgress(100);
}
//AsyncTask
class AsyncLoader extends AsyncTask<Void, Void, Integer>{
@Override
protected Integer doInBackground(Void... params) {
initProgress();
return null;
}
}
}
获取网页的例子:
//设置三种类型参数分别为 String,Integer,String
class PageTask extends AsyncTask<String, Integer, String> {
// 可变长的输入参数,与 AsyncTask.exucute()对应
@Override
protected String doInBackground(String... params) {
try {
HttpClient client = new DefaultHttpClient();
// params[0] 代表连接的 url
HttpGet get = new HttpGet(params[0]);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
String s = null;
if (is != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[128];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
if (length > 0) {
// 如果知道响应的长度,调用 publishProgress()更新进度
publishProgress((int) ((count / (float) length) * 100));
}
// 为了在模拟器中清楚地看到进度,让线程休眠 100ms
Thread.sleep(100);
}
s = new String(baos.toByteArray()); }
// 返回结果
return s;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
评论