使用 Picasso 下载多张图片

Downloading multiple pictures with Picasso

我正在尝试使用 picasso 下载多张图片。这是我的代码:

for(int i=1; i <=20; i++){
    String url = img_url + i + "/profile.jpg";
    String img_dir = img_dir + i;
    Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));

}

Url 的站点如下所示:

site.com/img/equipment/1/profile.jpg, 
site.com/img/equipment/2/profile.jpg, 
site.com/img/equipment/3/profile.jpg

等等...

我试过了

Picasso.with(this).load(url).into(picassoImageTarget(getApplicationContext(),img_dir, img_name));

没有 for 循环,它正在运行。当我把它放在循环中时,图像没有下载。

这是我的目标

private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
    Log.d("picassoImageTarget", " picassoImageTarget");
    ContextWrapper cw = new ContextWrapper(context);
    final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
    return new Target() {
        @Override
        public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final File myImageFile = new File(directory, imageName); // Create image file
                    FileOutputStream fos = null;
                    try {
                        fos = new FileOutputStream(myImageFile);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                   Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());

                }
            }).start();
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
        }
        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            if (placeHolderDrawable != null) {}
        }
    };
}

请帮忙。谢谢。

Targets are held in WeakReferences.

您需要保留对要保留的目标的引用,以防止它们被垃圾回收。

也许您的代码类似于:

final class MyLoader {
  final ArrayList<Target> targets = new ArrayList<>(20);
  void load(...) {
    for(...) {
      Target target = picassoImageTarget(...);
      targets.add(target);
      picasso.load(...).into(target); // TODO: Maybe remove from list when complete.
    }
  }
}