Android 4.4及以上版本写入外置SD卡问题

1 获取外置SD卡的路径
由于现在大多数手机都是带有内存的,原本获取外置SD卡路径的方法Environment.getExternalStorageDirectory() 获取得到的是手机自身内存的根目录。那么我们要怎么来获取到外置SD卡的路径,首先需要判断是否挂载了sdk,同样的Environment.getExternalStorageState()这个方法判断的只是机身内存空间,需要额外写一个工具类进行判断。这里要用到的是java的反射机制,下面是代码:

public class SDMountUtil {
   
    /**
     * 判断是否挂载外置sd卡
     * @param context
     * @return
     */
    public static boolean sdMounted(Context context){
        boolean mounted=false;
        StorageManager sm=(StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
        try {
            Method getVolumList=StorageManager.class.getMethod("getVolumeList");
            getVolumList.setAccessible(true);
            Object []results=(Object[]) getVolumList.invoke(sm);
            if(results!=null){
                for(Object result:results){
                    Method mRemoveable=result.getClass().getMethod("isRemovable");
                    Boolean isRemovable=(Boolean) mRemoveable.invoke(result);
                    if(isRemovable){
                        Method getPath=result.getClass().getMethod("getPath");
                        String path=(String) getPath.invoke(result);
                        Method getState=sm.getClass().getMethod("getVolumeState", String.class);
                        String state=(String) getState.invoke(sm, path);
                        if(state.equals(Environment.MEDIA_MOUNTED)){
                            mounted=true;
                            break;
                        }

                    }
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.pr
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值