Android 下载到SD卡 踩坑(Retrofit2)

发布于 2018-11-15  80 次阅读


1.权限

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

2.动态申请

RxPermissions permissions = new RxPermissions(this)
if (permissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
    toDownload();
}else{
    Disposable subscribe = permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
          .subscribe(granted -> {
              if (granted) {
                  toDownload();
              }
          });
      rxDisposable(subscribe);
}

3.下载

public void download(Call<ResponseBody> call, KListener listener) {
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response == null || response.body() == null) {
                listener.onError("Image source error");
                return;
            }
            if (writeResponseBodyToDisk(response.body())) {
                listener.onSuccess();
            } else {
                listener.onError("Image source error");
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            listener.onError("Image source error");
        }
    });
}

4.刷到SD卡

private static boolean writeResponseBodyToDisk(ResponseBody body) {
    try {
        InputStream is = body.byteStream();
        File fileDr = new File(Constant.getDownloadPath());
        if (!fileDr.exists()) {
            fileDr.mkdir();
        }
        File file = new File(Constant.getDownloadPath(), System.currentTimeMillis() + ".jpg");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
        fos.close();
        bis.close();
        is.close();
        return true;
    } catch (IOException e) {
        return false;
    }
}

路径:

private static String DownloadPath;//下载路径

public static String getDownloadPath() {
    if (UText.isEmpty(DownloadPath)) {
       //错误示范
       DownloadPath = Environment.getDataDirectory().getPath() + 
            File.separator + getSPName() + File.separator;
    }
    return DownloadPath;
}

5.踩坑记录

5.1.坑点

Environment.getDataDirectory().getPath()这样获取的路径始终创建失败,

5.2.正确姿势

换成Environment.getExternalStorageDirectory().getAbsolutePath()这样直接就成功了.

5.3.打印
Environment.getDataDirectory().getPath() + File.separator + name;
--->/data/name
Environment.getExternalStorageDirectory().getAbsolutePath()+ File.separator + name;
--->/storage/emulated/0/name

赤夜染尽 千樱散落 零时夜雨 无茵之音