使用Picasso Library无法下载图像并将其保存在本地存储中

时间:2018-01-08 11:59:18

标签: android picasso

我正在尝试使用Picasso库下载图像,然后将图像保存到本地存储中。 错误:在方法getImage()的日志“内部getImage”之后,logcat显示来自onBitmapFailed(Drawable errorDrawable)的日志。 我只能找到将目标引用转换为强引用的示例。但是,这并没有解决问题。

以下是我编写的用于下载和保存图片的代码片段:

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;


public class DownloadImage {

    Context mContext;
    Target target;

    public void getImage(Context context) {
        mContext = context;
        String path = "/data/data/ops.com.imagefetcher/images";
        Picasso.with(context)
                .load("http://blog.concretesolutions.com.br/wp-content/uploads/2015/04/Android1.png")
                .into(getTarget(path));
        Log.e("Download Image: ", "inside  getImage()");
    }

    private Target getTarget(final String path) {
//        ContextWrapper cw = new ContextWrapper(mContext);
//        final File directory = cw.getDir(path, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir

        target = new Target() {
            @Override
            public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("Download Image: ", "inside  run");
                        final File myImageFile = new File(Environment.getExternalStorageDirectory().getPath() + "/" + path, "example");
                        FileOutputStream ostream = null;
                        try {
                            Log.e("Download Image: ", "inside  try");
                            myImageFile.createNewFile();
                            ostream = new FileOutputStream(myImageFile);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                            ostream.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                ostream.close();
                                Log.e("Download Image: ", "inside  finally");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        Log.e("Download Image: ", "image saved to >>>" + myImageFile.getAbsolutePath());
                    }
                }).start();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                Log.e("Download Image: ", "error!");

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        return target;
    }
}

清单文件是:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ops.com.imagefetcher">

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"
            android:enabled="true"
            android:exported="true"/>
    </application>

</manifest>

LogCat输出:这是我在日志中获得的,没有别的。

 01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/Download Image:: before target
01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/Download Image:: inside  getImage()
01-09 19:56:26.964 30021-30021/ops.com.imagefetcher E/MyService:: below getImage()
01-09 19:56:27.884 30021-30111/ops.com.imagefetcher D/dalvikvm: GC_FOR_ALLOC freed 314K, 12% free 3109K/3500K, paused 2ms, total 2ms

1 个答案:

答案 0 :(得分:1)

使用默认DownloadManager下载图片

  private long downloadFile( String uRl, String desc, String name) {

    File direct = new File(Environment.getExternalStorageDirectory()
            + "/MyFolderName");

    if (!direct.exists()) {
        direct.mkdirs();
    }

    DownloadManager mgr = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);

    Uri downloadUri = Uri.parse(uRl);
    DownloadManager.Request request = new DownloadManager.Request(
            downloadUri);

    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle(name)
            .setDescription(desc)
            .setVisibleInDownloadsUi(true)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setDestinationInExternalFilesDir(context,"/MyFolderName", name + ".jpg")
            .setDestinationInExternalPublicDir("/MyFolderName", name + ".jpg");

     return mgr.enqueue(request);
}

只需将网址传递给此方法即可。它将完成所有必需的流程