Can't create folder on external storage on android

后端 未结 8 1067
独厮守ぢ
独厮守ぢ 2020-12-05 11:25

My development phone is a Nexus 5, running Android 4.4.2.

In my application, I am attempting to create a folder on external storage that wi

8条回答
  •  囚心锁ツ
    2020-12-05 12:02

    For android sdk version 23 and above you should check if the user has granted permission of external storage.

    private void createFolder() {
        if (isStoragePermissionGranted()) {
            File folder = new File(Environment.getExternalStorageDirectory()+ File.separator + "DebugData");
    
            if(!folder.exists()){
                folder.mkdir();
            }
        }
    
    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            return true;
        }
    }
    

    The code above worked for me and I hope it will work for you.

提交回复
热议问题