Micro Sd卡检测

时间:2011-08-23 05:53:48

标签: android android-sdcard

有没有办法检测android中的micro sd卡?我知道Environment类提供了外部存储细节。但它只是给出了内置的SD卡细节。有办法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用isExternalStorageEmulated()来确定当前的“外部”存储实际上是真正的外部存储还是仅仅是内部存储的一部分。如果它是真的那么你应该得到可移动卡的属性。

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分: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://", "");
                }
            }
        }
    }