0

How can I get SD Card directory in Android API Level 11? This code

Environment.getExternalStorageDirectory();

returns me directory of phone memory (internal directory). I added permissions to AndroidManifest.xml only for External Storage:

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

On some phones this code works correctly (for example, ZTE Blade HN and Phillips), e.t. returns concretically SD Card path. But Lenovo returns Internal path. Every phone has official recovery.

nick
  • 197
  • 1
  • 2
  • 16

2 Answers2

0
public static HashSet<String> getExternalMounts() {
    final HashSet<String> out = new HashSet<String>();
    String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
    String s = "";
    try {
        final Process process = new ProcessBuilder().command("mount")
                .redirectErrorStream(true).start();
        process.waitFor();
        final InputStream is = process.getInputStream();
        final byte[] buffer = new byte[1024];
        while (is.read(buffer) != -1) {
            s = s + new String(buffer);
        }
        is.close();
    } catch (final Exception e) {
        e.printStackTrace();
    }

    // parse output
    final String[] lines = s.split("\n");
    for (String line : lines) {
        if (!line.toLowerCase(Locale.US).contains("asec")) {
            if (line.matches(reg)) {
                String[] parts = line.split(" ");
                for (String part : parts) {
                    if (part.startsWith("/"))
                        if (!part.toLowerCase(Locale.US).contains("vold"))
                            out.add(part);
                }
            }
        }
    }
    return out;
}

The original method was tested and worked with my phone

Ali Radman
  • 184
  • 1
  • 13
0

In some devices external sdcard default name is showing as extSdCard and for other it is sdcard1. This code snippet helps to find out that exact path and helps to retrive you the path of external devices too like when phone is attached with laptop.

private String[] getPaths()
{
  String[] paths = new String[4];

if(new File("/storage/extSdCard/").exists()) 
  paths[0]="/storage/extSdCard/";
if(new File("/storage/sdcard1/").exists()) 
  paths[1]="/storage/sdcard1/";
if(new File("/storage/usbcard1/").exists())  
  paths[2]="/storage/usbcard1/"; 
if(new File("/storage/sdcard0/").exists()) 
  paths[3]="/storage/sdcard0/";

 return paths;
}
Zain Ul Abidin
  • 2,467
  • 1
  • 17
  • 29