简体   繁体   中英

How to get the internal and external sdcard path in android

Most of the new android devices have an internal sdcard and an external sdcard. I want to make a file explorer app but I can't find out how to get the path to use in my app because

File file = Environment.getExternalStorageDirectory();

How to get the internal and external sdcard path in android

Methods to store in Internal Storage:

File getDir (String name, int mode)

File getFilesDir () 

Above methods are present in Context class

Methods to store in phone's internal memory:

File getExternalStorageDirectory ()

File getExternalFilesDir (String type)

File getExternalStoragePublicDirectory (String type)

In the beginning, everyone used Environment.getExternalStorageDirectory() , which pointed to the root of phone's internal memory. As a result, root directory was filled with random content.

Later, these two methods were added:

In Context class they added getExternalFilesDir() , pointing to an app-specific directory on phone's internal memory. This directory and its contents will be deleted when the app is uninstalled.

Environment.getExternalStoragePublicDirectory() for centralized places to store well-known file types, like photos and movies. This directory and its contents will NOT be deleted when the app is uninstalled.

Methods to store in Removable Storage ie micro SD card

Before API level 19, there was no official way to store in SD card. But many could do it using unofficial APIs.

Officially, one method was introduced in Context class in API level 19 (Android version 4.4 - Kitkat).

File[] getExternalFilesDirs (String type)

It returns absolute paths to application-specific directories on all shared/external storage devices where the application can place persistent files it owns. These files are internal to the application, and not typically visible to the user as media.

That means, it will return paths to both Micro SD card and Internal memory. Generally, second returned path would be storage path of micro SD card.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Yes. Different manufacturer use different SDcard name like in Samsung Tab 3 its extsd, and other samsung devices use sdcard like this different manufacturer use different names.

I had the same requirement as you. so i have created a sample example for you from my project goto this link Android Directory chooser example which uses the androi-dirchooser library. This example detect the SDcard and list all the subfolders and it also detects if the device has morethan one SDcard.

Part of the code looks like this For full example goto the link Android Directory Chooser

/**
* Returns the path to internal storage ex:- /storage/emulated/0
 *
* @return
 */
private String getInternalDirectoryPath() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
 }

/**
 * Returns the SDcard storage path for samsung ex:- /storage/extSdCard
 *
 * @return
 */
    private String getSDcardDirectoryPath() {
    return System.getenv("SECONDARY_STORAGE");
}


 mSdcardLayout.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        String sdCardPath;
        /***
         * Null check because user may click on already selected buton before selecting the folder
         * And mSelectedDir may contain some wrong path like when user confirm dialog and swith back again
         */

        if (mSelectedDir != null && !mSelectedDir.getAbsolutePath().contains(System.getenv("SECONDARY_STORAGE"))) {
            mCurrentInternalPath = mSelectedDir.getAbsolutePath();
        } else {
            mCurrentInternalPath = getInternalDirectoryPath();
        }
        if (mCurrentSDcardPath != null) {
            sdCardPath = mCurrentSDcardPath;
        } else {
            sdCardPath = getSDcardDirectoryPath();
        }
        //When there is only one SDcard
        if (sdCardPath != null) {
            if (!sdCardPath.contains(":")) {
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File(sdCardPath);
                changeDirectory(dir);
            } else if (sdCardPath.contains(":")) {
                //Multiple Sdcards show root folder and remove the Internal storage from that.
                updateButtonColor(STORAGE_EXTERNAL);
                File dir = new File("/storage");
                changeDirectory(dir);
            }
        } else {
            //In some unknown scenario at least we can list the root folder
            updateButtonColor(STORAGE_EXTERNAL);
            File dir = new File("/storage");
            changeDirectory(dir);
        }


    }
});

Since there is no direct meathod to get the paths the solution may be Scan the /system/etc/vold.fstab file and look for lines like this: dev_mount sdcard /mnt/sdcard 1 /devices/platform/s3c-sdhci.0/mmc_host/mmc0

When one is found, split it into its elements and then pull out the path to the that mount point and add it to the arraylist

emphasized text some devices are missing the vold file entirely so we add a path here to make sure the list always includes the path to the first sdcard, whether real or emulated.

    sVold.add("/mnt/sdcard");

    try {
        Scanner scanner = new Scanner(new File("/system/etc/vold.fstab"));
        while (scanner.hasNext()) {
            String line = scanner.nextLine();
            if (line.startsWith("dev_mount")) {
                String[] lineElements = line.split(" ");
                String element = lineElements[2];

                if (element.contains(":"))
                    element = element.substring(0, element.indexOf(":"));

                if (element.contains("usb"))
                    continue;

                // don't add the default vold path
                // it's already in the list.
                if (!sVold.contains(element))
                    sVold.add(element);
            }
        }
    } catch (Exception e) {
        // swallow - don't care
        e.printStackTrace();
    }
}

Now that we have a cleaned list of mount paths, test each one to make sure it's a valid and available path. If it is not, remove it from the list.

private static void testAndCleanList() 
{
    for (int i = 0; i < sVold.size(); i++) {
        String voldPath = sVold.get(i);
        File path = new File(voldPath);
        if (!path.exists() || !path.isDirectory() || !path.canWrite())
            sVold.remove(i--);
    }
}

I'm not sure how general an answer this but I tested it on a motorola XT830C with Android 4.4 and on a Nexus 7 android 6.0.1. and on a Samsung SM-T530NU Android 5.0.2. I used System.getenv("SECONDARY_STORAGE") and Environment.getExternalStorageDirectory().getAbsolutePath() .
The Nexus which has no second SD card, System.getenv returns null and Envirnoment.getExterna... gives /storage/emulated/0.
The motorola device which has an external SD card gives /storage/sdcard1 for System.getenv("SECONDARY_STORAGE") and Envirnoment.getExterna... gives /storage/emulated/0.
The samsumg returns /storage/extSdCard for the external SD.
In my case I am making a subdirectory on the external location and am using

 appDirectory = (System.getenv("SECONDARY_STORAGE") == null)
       ? Environment.getExternalStorageDirectory().getAbsolutePath()
       : System.getenv("SECONDARY_STORAGE");

to find the sdcard. Making a subdirectory in this directory is working.
Of course I had to set permission in the manifest file to access the external memory.
I also have a Nook 8" color tablet. When I get a chance to test on them, I'll post if I have any problems with this approach.

but there is another path for the other external sdcard like /storage1 or /storage2

There is nothing in the Android SDK -- at least through Android 4.1 -- that gives you access to those paths. They may not be readable or writable by your app, anyway. The behavior of such storage locations, and what they are used for, is up to device manufacturers.

Try this code it will help

Map<String, File> externalLocations = ExternalStorage.getAllStorageLocations();
File sdCard = externalLocations.get(ExternalStorage.SD_CARD);
File externalSdCard = externalLocations.get(ExternalStorage.EXTERNAL_SD_CARD);
File main=new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()));
File[]t=main.getParentFile().listFiles();

for(File dir:t)
{
    Log.e("Main",dir.getAbsolutePath());
}

Output:

E/Main: /storage/sdcard1
E/Main: /storage/sdcard0

I have one SD card and inbuilt memory.

For all Android versions,

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />

There is no public api for get internal/external sdcard path.

But there is platform api called StorageManager in android.os.storage package. see http://goo.gl/QJj1eu .

There are some features such as list storage, mount/unmount storage, get mount state, get storage path, etc.

But it is hidden api and it should be deprecated or broken in next android release.

And some methods need special permission, and most are not Documented.

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