Reason: java.lang.illegalstateexception: unable to create directory in Android 6.0 device

I have to use the downloadmanager to store the downloaded image from the URL and store it in an SD card with my own directory (such as "XYZ"). This is my code

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);
}

This code will run to Android 5.1.1. When I run the same code in 6.0, it will cause an error like this

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)

I added read and write permissions to the manifest file. How can I resolve this error? Anyone can help me? Thank you in advance

resolvent:

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)

The problem seems to be related to the Android runtime permission introduced in Android 6.0

When your application is positioned as API level 23 or higher, all permissions are false by default. To solve this problem, you must apply for the permission dialog box and approve the permission before it can be used in your application

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>