Android AsyncTask 详解
2010-11-05 00:55:35 来源:WEB开发网/*
* 此方法在后台线程执行,完成任务的主要工作,通常需要较长的时间。
* 在执行过程中可以调用publicProgress(Progress…)来更新任务的进度。
*/
Log.i("czb", "doInBackground is running...");
try {
Bitmap bitmap;
HttpClient client = new DefaultHttpClient();
// params[0]代表连接的url
URI uri = URI.create((String) params[0]);
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
Log.i("czb", " " + length);
InputStream in = entity.getContent();
if (in != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
/*byte[] buf = new byte[128];
int ch = -1;
int count = 0;
while ((ch = in.read(buf)) != -1) {
baos.write(buf, 0, ch);
count += ch;
if (length > 0) {
// 如果知道响应的长度,调用publishProgress()更新进度
// onProgressUpdate读取进度
publishProgress((int) ((count / (float) length) * 100));
}
// 为了在模拟器中清楚地看到进度,让线程休眠100ms
//Thread.sleep(100);
}*/
bitmap = BitmapFactory.decodeStream(in);
in.close();
baos.close();
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
更多精彩
赞助商链接