因为客户APP需要有一键下载当前图片集合的功能,所以开始研究如何实现下载多张网络图片。刚开始只是简单地使用for循环去遍历每一个网络图片,然后进行下载。但是如此做有以下缺点:1.因为是同时开启下载线程,所以有时会漏掉几张图片(具体原因不明)。2.没办法监听下载状态,下载完成时没有办法及时通知用户。基于以上原因,故使用异步任务AsyncTask。
private class Mytask extends AsyncTask<List<String>,Integer,String>{
@Override
protected String doInBackground(List<String>... params) {
List<String> list = params[0];
File file = null;
Bitmap bitmap = null;
HttpURLConnection conn = null;
FileOutputStream outStream = null;
InputStream is = null;
try {
for (String imageurl:list) {
file = createStableImageFile(mContext);
URL url = new URL(imageurl);
conn = (HttpURLConnection) url.openConnection();
conn.connect();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
file.getAbsolutePath(), file.getAbsolutePath(), null);
// 最后通知图库更新
mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
is.close();
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// ToastUtil.show("下载完成");
}
}
//创建本地保存路径
private static File createStableImageFile(Context context){
String fileName = System.currentTimeMillis() + ".jpg";//存放的文件名
File storageDir = context.getExternalCacheDir();
File image = new File(storageDir, fileName);
return image;
}
在执行下载方法的地方:
new Mytask().execute(arr); //arr为网络图片地址集合 ArrayList<String> arr