我需要通过 URL 加载图像,在 ImageView 中设置并将文件保存在 SD 卡中。
这堂课会这样做,但速度很慢...... jpg 文件有 60kb,在我的 10Mbps 互联网连接中下载它的时间为 3~6 秒......
我正在使用它来加载列表视图中的任何图像......
公共类 DownloadImageTask 扩展 AsyncTask {
ImageView bmImage;
String path;
String filename = "pg0.rsc";
String param;
Context context;
public DownloadImageTask(Context context, ImageView bmImage, String param, String code) {
this.bmImage = bmImage;
this.param = param;
this.path = Environment.getExternalStorageDirectory().toString() + "/.RascunhoCache/." + code + "/";
this.context = context;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
if(param.equals("c")){
OutputStream outStream = null;
new File(path).mkdirs();
File file = new File(path, filename);
try {
outStream = new FileOutputStream(file);
result.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
}
catch(Exception e){}
}
}
}