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

最近发现以前网上搜索的判断外置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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值