先看使用这个类
在主线程中执行下面这两个步骤即可
diTask = new DownloadImageTask(this);
diTask.execute(url);
DownloadImageTask是AsyncTask的子类。
execute(url)函数的参数类型是AsyncTask模板类第一个参数类型。
需要自己继承AsyncTask模板类,并实现它的四个方法。
AsyncTask<String, Integer, Bitmap>
第一个类型为doInBackground函数的参数类型
第二个参数为onProgressUpdate函数的参数的类型,跟新界面用的
第三个为doInBackground返回和onPostExecute传入的参数类型
public class DownloadImageTask extends AsyncTask<String, Integer, Bitmap> {
private Context mContext;DownloadImageTask(Context context) {
mContext = context;
}
//在背景线程运行之前执行,用于初始化,比如创建一个进度条之类的。
// We could do some setup work here before doInBackground() runs
}
//运行在背景线程中,执行耗时任务,不能更新ui
Log.v("doInBackground", "doing download of image");
return downloadImage(urls);
}
//根据publishProgress的报告更新ui
TextView mText = (TextView) ((Activity) mContext).findViewById(R.id.text);
mText.setText("Progress so far: " + progress[0]);
}
//背景线程运行 完毕后执行,可以更新ui
if(result != null) {
ImageView mImage = (ImageView) ((Activity) mContext).findViewById(R.id.image);
mImage.setImageBitmap(result);
}
else {
TextView errorMsg = (TextView) ((Activity) mContext).findViewById(R.id.errorMsg);
errorMsg.setText("Problem downloading image. Please try again later.");
}
}
private Bitmap downloadImage(String... urls)
{
HttpClient httpClient = CustomHttpClient.getHttpClient();
try {
HttpGet request = new HttpGet(urls[0]);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 60000); // 1 minute
request.setParams(params);
publishProgress(25);
HttpResponse response = httpClient.execute(request);
publishProgress(50);
byte[] image = EntityUtils.toByteArray(response.getEntity());
publishProgress(75);
Bitmap mBitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
publishProgress(100);
return mBitmap;
} catch (IOException e) {
// covers:
// ClientProtocolException
// ConnectTimeoutException
// ConnectionPoolTimeoutException
// SocketTimeoutException
e.printStackTrace();
}
return null;
}
}
参考文章:http://www.cnblogs.com/xingmeng/archive/2012/05/24/2516481.html