原因:java.lang.IllegalStateException:无法在Android 6.0设备中创建目录

mal*_*ika 5 android android-sdcard imagedownload android-download-manager

我必须使用DownloadManager存储从url下载的图像,并将其存储到sdcard中,并带有我自己的目录,例如“ xyz”。这是我的代码

File img_directory = null;

img_directory = new File(Environment.getExternalStorageDirectory() + "/xyz");
if (!img_directory.exists()) {
    img_directory.mkdirs();
    DownloadManager mgr = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri downloadUri = Uri.parse("my image url");
    DownloadManager.Request request = new DownloadManager.Request(downloadUri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
      .setAllowedOverRoaming(true)
      .setTitle("Demo")
      .setDescription("Something useful. No, really.")
      .setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
      .setDestinationInExternalPublicDir(Environment.getExternalStorageDirectory().getAbsolutePath() + "/xyz", image.jpeg);
    mgr.enqueue(request);
}
Run Code Online (Sandbox Code Playgroud)

此代码将在Android 5.1.1上运行。当我在6.0中运行相同的代码时,会引发如下错误

Caused by: java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/storage/emulated/0/xyz at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:538)
Run Code Online (Sandbox Code Playgroud)

我已在清单文件中添加了“读取”和“写入”权限。如何解决此错误?有谁能帮助我?提前致谢。

And*_*123 4

Caused by: java.lang.IllegalStateException: Unable to create directory: /storage/emulated/0/storage/emulated/0/xyz at android.app.DownloadManager$Request.setDestinationInExternalPublicDir(DownloadManager.java:538)
Run Code Online (Sandbox Code Playgroud)

问题似乎与Android 6.0 中引入的Android Runtime Permission有关

当您的应用定位为 API 级别 23 或更高级别时,默认情况下所有权限均为false. 要解决此问题,您必须请求权限对话框并批准该权限,然后再将其用于您的应用程序。