2014-12-09 70 views
0

雖然我有這麼多的帖子,但問題是, 它返回true,如果手機有建立存儲。 任何人幫我檢查SD卡是否可用或編程方式在Android

+2

Android SDK沒有這方面的內容,因爲Android不支持[可移動存儲](http://commonsware.com/blog/2 014/04/09/storage-situation-removable-storage.html),並且4.4+中的支持不包括您正在尋找的內容。 – CommonsWare 2014-12-09 12:54:41

回答

1

使用這樣的:

Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 

if(isSDPresent) 
{ 
    // yes SD-card is present 
} 
else 
{ 
// Sorry 
} 
+0

我已經在Tab(版本4.2.2)中測試了這個,並且沒有任何存儲卡,使用上面的代碼返回true [email protected] Maurya – 2014-12-11 04:50:28

+0

我認爲在4.4之前沒有任何實際的外部存儲支持。 – nasch 2015-01-01 23:49:43

+0

該方法檢查是否有任何存儲卡可用。如果設備有任何卡來存儲包括內部存儲在內的數據,它將返回true。所以如果一個設備有一個內部存儲器,那麼這個方法總是返回true – Sudara 2015-12-26 08:21:17

0

下面的代碼將有助於...

/** 
* Returns all available external SD-Card roots in the system. 
* 
* @return paths to all available external SD-Card roots in the system. 
*/ 
public static String[] getStorageDirectories() { 
    String[] storageDirectories; 
    String rawSecondaryStoragesStr = System.getenv("SECONDARY_STORAGE"); 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     List<String> results = new ArrayList<String>(); 
     File[] externalDirs = myContext.getExternalFilesDirs(null); 
     for (File file : externalDirs) { 
      String path = null; 
      try { 
       path = file.getPath().split("/Android")[0]; 
      } catch (Exception e) { 
       e.printStackTrace(); 
       path = null; 
      } 
      if (path != null) { 
       if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Environment.isExternalStorageRemovable(file)) 
         || rawSecondaryStoragesStr != null && rawSecondaryStoragesStr.contains(path)) { 
        results.add(path); 
       } 
      } 
     } 
     storageDirectories = results.toArray(new String[0]); 
    } else { 
     final Set<String> rv = new HashSet<String>(); 

     if (!TextUtils.isEmpty(rawSecondaryStoragesStr)) { 
      final String[] rawSecondaryStorages = rawSecondaryStoragesStr.split(File.pathSeparator); 
      Collections.addAll(rv, rawSecondaryStorages); 
     } 
     storageDirectories = rv.toArray(new String[rv.size()]); 
    } 
    return storageDirectories; 
} 

//檢查外部SD是否可用

String retArray[] = getStorageDirectories(); 
    if (retArray.length == 0) { 
     Toast.makeText(ListenActivity.this, "Sdcard not Exists", Toast.LENGTH_SHORT).show(); 
    } else { 
     for (int i = 0; i < retArray.length; i++) {    
      Log.e("path ", retArray[i]); 
      } 
    } 
相關問題