android5.1判断外置SD卡是否存在

来源:互联网 发布:仿真分析软件 编辑:程序博客网 时间:2024/06/05 06:31

最近发现以前网上搜索的判断外置SD是否存在的方法在android5.1上不能使用了,上网和看源码找到了一个方法可以判断SD卡是否存在。

private boolean isExternalStorageMounted() {    final StorageVolume[] volumes = mStorageManager.getVolumeList();    for (StorageVolume v : volumes) {        if (v.isRemovable()) {            if (Environment.MEDIA_MOUNTED.equals(Environment.getStorageState(v.getPathFile())))                return true;        }    }    return false;}

首先要在oncreate方法里初始化mStorageManager
mStorageManager = StorageManager.from(this);

此方法我验证过,可以使用。
网上别人的文档:

通过正规api得不到外卡路径.

谷歌在源码中给出了得到外卡路径的方法,但标记为隐藏接口,因此api无法访问.

可以通过反射接口得到:

import java.lang.reflect.Method;import android.os.storage.StorageManager;     public String getPrimaryStoragePath() {        try {            StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);            // first element in paths[] is primary storage path            return paths[0];        } catch (Exception e) {            Log.e(TAG, "getPrimaryStoragePath() failed", e);        }        return null;    }        public String getSecondaryStoragePath() {        try {            StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);            Method getVolumePathsMethod = StorageManager.class.getMethod("getVolumePaths", null);            String[] paths = (String[]) getVolumePathsMethod.invoke(sm, null);            // second element in paths[] is secondary storage path            return paths[1];        } catch (Exception e) {            Log.e(TAG, "getSecondaryStoragePath() failed", e);        }        return null;    }        public String getStorageState(String path) {        try {            StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);            Method getVolumeStateMethod = StorageManager.class.getMethod("getVolumeState", new Class[] {String.class});            String state = (String) getVolumeStateMethod.invoke(sm, path);            return state;        } catch (Exception e) {            Log.e(TAG, "getStorageState() failed", e);        }        return null;    }

 

如果楼主有源码,可以去找StorageManager这个类,拉到文件最下方,就可以看到那三个隐藏接口.



0 0
原创粉丝点击