20

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();

just returns in most device /mnt/sdcard but there is another path for the other external sdcard like /storage1 or /storage2 . Any help appreciated.

Mahmoud Jorban
  • 952
  • 4
  • 13
  • 25

8 Answers8

12

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 i.e. 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.

CL.
  • 173,858
  • 17
  • 217
  • 259
AnV
  • 2,794
  • 3
  • 32
  • 43
2

For all Android versions,

Permissions:

<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" />

Use requestLegacyExternalStorage for Android 10 (add to AndroidManifest > application tag):

android:requestLegacyExternalStorage="true"

Get internal directory path:

@Nullable
public static String getInternalStorageDirectoryPath(Context context) {
    String storageDirectoryPath;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
        if(storageManager == null) {
            storageDirectoryPath = null; //you can replace it with the Environment.getExternalStorageDirectory().getAbsolutePath()
        } else {
            storageDirectoryPath = storageManager.getPrimaryStorageVolume().getDirectory().getAbsolutePath();
        }
    } else {
        storageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    return storageDirectoryPath;
}

Get external directories:

@NonNull
public static List<String> getExternalStorageDirectoryPaths(Context context) {
    List<String> externalPaths = new ArrayList<>();
    String internalStoragePath = getInternalStorageDirectoryPath(context);

    File[] allExternalFilesDirs = ContextCompat.getExternalFilesDirs(context, null);
    for(File filesDir : allExternalFilesDirs) {
        if(filesDir != null) {
            int nameSubPos = filesDir.getAbsolutePath().lastIndexOf("/Android/data");
            if(nameSubPos > 0) {
                String filesDirName = filesDir.getAbsolutePath().substring(0, nameSubPos);
                if(!filesDirName.equals(internalStoragePath)) {
                    externalPaths.add(filesDirName);
                }
            }
        }
    }

    return externalPaths;
}
Atakan Yildirim
  • 684
  • 11
  • 22
1

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 textsome 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--);
    }
}
Emel Elias
  • 572
  • 7
  • 18
1

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.

driftking9987
  • 1,673
  • 1
  • 32
  • 63
steven smith
  • 1,519
  • 15
  • 31
0

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Ok, but how can I know if the device has internal and external sdcard by code – Mahmoud Jorban Nov 13 '12 at 13:07
  • 2
    @Ma7moudHatem: There is nothing in the Android SDK -- at least through Android 4.1 -- that tells you "if the device has internal and external sdcard by code". – CommonsWare Nov 13 '12 at 13:27
  • @MahmoudHatem for finding the proper location of internal or external sdcard u have to use DDMS in your android SDK. – UchihaSasuke May 20 '14 at 03:18
  • 1
    No, DDMS will give answers which apply to adb, but often not to apps, which see the same storage at different paths than adb does. – Chris Stratton Aug 07 '14 at 04:25
0
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.

Pang
  • 9,564
  • 146
  • 81
  • 122
kumar
  • 1
-1

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.

ganachoco
  • 302
  • 1
  • 3
-1

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);
Rahul
  • 479
  • 3
  • 18