Caused by: java.lang.IllegalStateException: Unable to create directory in Android 6.0 devices

后端 未结 3 1249
野趣味
野趣味 2021-01-18 09:17

I have to store the download the image from the url using DownloadManager and store it into the sdcard with my own directory like \"xyz\". This is my code

Fi         


        
3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 09:56

    As answered above, you need to request the permission you need (in this case, you need the WRITE_EXTERNAL_STORAGE permission), since you are attempting to create a directory in the external storage.

    To do so, you need to check that you are either allowed to use that permission or to request it to the user otherwise. This is a sample code:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (context.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity!!, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0);
        }
    }
    

    As you can see, this is only necessary if the version is equal or higher than M (Android SDK Version 23).

    If the user is required to grant permission, then you'll need a way of coming back to your desired point in the code, where you can continue. To do so, you first need to override the onRequestPermissionsResult method, in order to receive the response of the user (if the user decided to grant the requested permission or not):

    @Override
    public void onRequestPermissionsResult(
            int requestCode, String permissions[], int[] grantResults
    ) {
        if (requestCode == REQUIRED_PERMISSIONS_REQUEST) {
            int index = 0;
            Map permissionsMap = new HashMap<>();
            for (String permission : permissions) {
                permissionsMap.put(permission, grantResults[index]);
                index++;
            }
    
            if (permissionsMap.containsKey(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    && permissionsMap.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == 0) {
                //
                // Call your code from here
                //
            }
        }
    }
    

提交回复
热议问题