简体   繁体   中英

Android 9 can't create directory inside Android external public path("storage/emulated/0/MyImages")

I want to create a directory inside Android external public path( "storage/emulated/0/MyImages" ).

The code is running on Android 9. All run-time permissions to writing on external storage are granted.

Tried code like this.

File dir = new File(Environment.getExternalStorageDirectory() + File.separator + "MyImages");
if (!dir.exists) {
  dir.mkdirs();
}

The dir variable has path - "/storage/emulated/0/MyImages" .

dir.mkdirs() always returns false . There is short log from LogCat:

W/System.err: java.io.IOException: No such file or directory
W/System.err: at java.io.UnixFileSystem.createFileExclusively0(Native Method)
W/System.err: at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
W/System.err: at java.io.File.createNewFile(File.java:1008)

First, check permission if yes then call your function else to call showPhoneStatePermission

Add permission in manifest

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

private void showPhoneStatePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            showExplanation("Permission Needed", "Rationale", Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
        } else {
            requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE);
        }
    } else {
        Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM