2016-11-05 71 views
0

如何在Android API級別11中獲取SD卡目錄?此代碼Environment.getExternalStorageDirectory()=內部目錄

Environment.getExternalStorageDirectory(); 

返回手機內存目錄(內部目錄)。我添加的權限AndroidManifest.xml僅用於外部存儲設備:

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

在一些手機這個代碼工作正常(例如,中興刀片HN和Phillips),E.T.具體返回SD卡路徑。但聯想返回內部路徑。每部手機都有官方恢復。

+0

看看[這](http://stackoverflow.com/q/40068984/6950238)quesion –

回答

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; 
} 

原來的方法進行了測試,並用我的手機

+0

是它工作在API級別11? –

+0

其在API +16 –

+0

上的工作但我需要11.我編輯問題。 –

0

在某些設備外部SD卡默認名稱顯示爲extSdCard工作和其他它是sdcard1。此代碼段有助於找出確切的路徑,並有助於爲您檢索外部設備的路徑,就像電話連接到筆記本電腦時一樣。

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; 
}