Android关于获取是否有外置sd卡以及内存使用情况的那些事儿

今天为大家分享下关于内存的事儿
可能很久之前,我们的获取是否有 外置内存是这样的(是否有sd卡以及sd卡相关内存信息)?

public static StatFs getSDMemory(Context context) {
    StatFs statfs = null;
    //判断是否有插入存储卡
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        //取得sdcard文件路径
        File path = Environment.getExternalStorageDirectory();
        statfs = new StatFs(path.getPath());
        //获取block的SIZE
    }


    return statfs;
}

由上面可知,(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) 这个即可获取是否有sd卡 。

但是到现在,毫无反应了 有木有!!!

变成了这样 :

public  static String getExtendedMemoryPath(Context mContext) {
    StorageManager mStorageManager = (StorageManager) mContext.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");
        Method getDescription = storageVolumeClazz.getMethod("getDescription", Context.class);
        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);
            String descprition = (String) getDescription.invoke(storageVolumeElement, mContext);
            if (removable && descprition.contains("SD")) {
                return path;
            }
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return null;
}

好了。差不多就是样子了。通过反射去拿这个isRemovable值,这个值代表是否有sd卡了。

你可能感兴趣的:(判断是否有sd卡,sd卡api变更)