2011-08-23 73 views
3

有沒有辦法在android中檢測微型SD卡?我知道Environment類提供了外部存儲細節。但它只是提供了內置的SD卡細節。有沒有辦法解決?微型SD卡檢測

回答

2

您可以使用isExternalStorageEmulated()來確定當前的「外部」存儲實際上是實際的外部存儲還是僅僅是內部存儲的一部分。如果它是真的,那麼你應該獲得可移動卡的屬性。

+0

但建議的方法犯規名單,而在Eclipse編寫代碼。 –

+0

它是在API級別11引入的 - 你在哪一個? –

1

試試這個:

boolean canSaveExternal = false; 
String storageState = Environment.getExternalStorageState(); 
if (Environment.MEDIA_MOUNTED.equals(storageState)) 
    canSaveExternal = true; 
else 
    canSaveExternal = false; 
+0

sry這考慮到了Android的內置sd卡而非外置可移動microSD卡。 –

0

Environment.getExternalStorageState()和Environment.getExternalStorageDirectory()將提供內置的SD卡,這是當前所有Android設備幾乎現有的現在。

兩種方法獲得「真正的」外部SD卡(或USB磁盤)。

  1. 使用getVolumeList()函數列出所有可移動存儲,請記住在訪問它之前檢查掛載狀態。

    private static String getExtendedMemoryPath(Context context) { 
        StorageManager mStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); 
        Class<?> storageVolumeClazz = null; 
        try { 
         storageVolumeClazz = Class.forName("android.os.storage.StorageVolume"); 
         Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList"); 
         Method getPath = storageVolumeClazz.getMethod("getPath"); 
         Method isRemovable = storageVolumeClazz.getMethod("isRemovable"); 
         Object result = getVolumeList.invoke(mStorageManager); 
         final int length = Array.getLength(result); 
         for (int i = 0; i < length; i++) { 
          Object storageVolumeElement = Array.get(result, i); 
          String path = (String) getPath.invoke(storageVolumeElement); 
          boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement); 
          if (removable) { 
           return path; 
          } 
         } 
        } catch (ClassNotFoundException e) { 
         e.printStackTrace(); 
        } catch (InvocationTargetException e) { 
         e.printStackTrace(); 
        } catch (NoSuchMethodException e) { 
         e.printStackTrace(); 
        } catch (IllegalAccessException e) { 
         e.printStackTrace(); 
        } 
        return null; 
    } 
    
  2. 註冊android.intent.action.MEDIA_MOUNTED事件,當存儲安裝,將廣播這個通知與安裝的磁盤路徑。

    <receiver android:enabled="true" android:name=".MountStatusReceiver"> 
         <intent-filter> 
          <action android:name="android.intent.action.MEDIA_MOUNTED"/> 
          <data android:scheme="file"/> 
         </intent-filter> 
        </receiver> 
    
    @Override 
    public void onReceive(Context context, Intent intent) { 
        if (intent != null) { 
          if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())) { 
           path = intent.getDataString().replace("file://", ""); 
          } 
         } 
        } 
    }