简体   繁体   中英

make external directory android

In case of making directory in external storage in android app I use this code:

File mDirectory = new File(Environment.getExternalStorageDirectory() + "/myDir");

        if (!mDirectory.exists()) {

            mDirectory.mkdirs();

            if (!mDirectory.mkdirs()) {
                Log.e("App", "failed to create directory");
            }
        }

but the directory didn't created and all the time the error message shown up in logcat :

App: failed to create directory

I also use both mkdir() and mkdirs() , but the result is same. where is the mistake?

updated:

AndroidManifest.xml

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

You are calling mkdirs twice. The first call creates the directory. The second call returns false, because the directory already exists.

What Android Version are you running this app on ? This quote from the Android Developer Website says

If the device is running Android 6.0 (API level 23) or higher , and the app's targetSdkVersion is 23 or higher, the app requests permissions from the user at run-time. The user can revoke the permissions at any time, so the app needs to check whether it has the permissions every time it runs .

If the device is running Android 5.1 (API level 22) or lower, or the app's targetSdkVersion is 22 or lower, the system asks the user to grant the permissions when the user installs the app.

Now there is a notion of Dangerous permissions . That are permissions the user needs to grant at runtime and WRITE_EXTERNAL_STORAGE is one of those

This tutorial on the Android Dev website will teach you how to request permission at runtime

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