android 获取外置SD卡路劲的方法

原文连接

原文连接

不同版本的安卓获取数据方式不一样

  • List item
    /**
    • 6.0使用此方法获取外置SD卡路径,尝试过反射
    • 但StorageVolume非Public API 编译不通过(7.0改为公开API),故使用UserEnvironment
    • 的内部方法getExternalDirs获取所有的路径,通过{@link Environment#isExternalStorageRemovable(File)}
    • 判断若removable则为外部存储
      */
      @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
      private static String getPhysicalExternalFilePathAboveM(){
      try {
      //===获取UserEnvironment
      Class<?> userEnvironment = Class.forName(“android.os.Environment$UserEnvironment”);
      Method getExternalDirs =userEnvironment.getDeclaredMethod(“getExternalDirs”);
      getExternalDirs.setAccessible(true);
      //获取构造UserEnvironment的必要参数UserId

      Class<?> userHandle = Class.forName(“android.os.UserHandle”);
      Method myUserId = userHandle.getDeclaredMethod(“myUserId”);
      myUserId.setAccessible(true);
      int mUserId = (int) myUserId.invoke(UserHandle.class);
      Constructor<?> declaredConstructor = userEnvironment.getDeclaredConstructor(Integer.TYPE);
      // 得到UserEnvironment instance
      Object instance = declaredConstructor.newInstance(mUserId);
      File[] files = (File[]) getExternalDirs.invoke(instance);
      for (int i = 0; i < files.length; i++) {
      if (Environment.isExternalStorageRemovable(files[i])){
      return files[i].getPath();
      }
      }
      } catch (Exception e) {
      Log.e(TAG,e.getMessage());
      }
      return “”;
      }

public static boolean copyFile(String source, String dest) {
try {
Log.e(TAG, “save 进入保存数据库方法 保存路劲=”+dest);
File f1 = new File(source);
File f0 = new File(dest);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f0);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, “copyFile保存数据库结果为false”,e);
}
return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值