当前位置:   article > 正文

Android获取手机内存与SD卡的根目录_android 获取sd卡根目录

android 获取sd卡根目录

直接贴出代码,有需要的可以直接变成工具类使用。优先读取sd卡假设没有sd卡再去手机内存中获取。记得动态配置读写权限!

  1. /**
  2. * 优先在SD卡,其次是内部存储
  3. */
  4. public static String getRWPath(Context context) {
  5. String rwPath = null;
  6. String storagePath = getStoragePath(context, true);
  7. if (null != storagePath) {
  8. rwPath = storagePath;
  9. } else {
  10. String sdPath = getSDPath();
  11. rwPath = sdPath;
  12. }
  13. return rwPath;
  14. }
  1. /**
  2. * @description 获取SD卡路径,不用在设置中这是默认存储位置
  3. */
  4. public static String getStoragePath(Context mContext, boolean is_removale) {
  5. StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
  6. Class<?> storageVolumeClazz = null;
  7. try {
  8. storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
  9. Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
  10. Method getPath = storageVolumeClazz.getMethod("getPath");
  11. Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
  12. Object result = getVolumeList.invoke(mStorageManager);
  13. final int length = Array.getLength(result);
  14. for (int i = 0; i < length; i++) {
  15. Object storageVolumeElement = Array.get(result, i);
  16. String path = (String) getPath.invoke(storageVolumeElement);
  17. boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
  18. if (is_removale == removable) {
  19. return path;
  20. }
  21. }
  22. } catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
  23. e.printStackTrace();
  24. }
  25. return null;
  26. }
  1. /**
  2. * 获取SD卡路径
  3. *
  4. * @return
  5. */
  6. public static String getSDPath() {
  7. String sdPath = null;
  8. // 判断sd卡是否存在
  9. boolean sdCardExit = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
  10. if (sdCardExit) {
  11. // 获取根目录
  12. sdPath = Environment.getExternalStorageDirectory().toString();
  13. }
  14. return sdPath;
  15. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/228190
推荐阅读
相关标签
  

闽ICP备14008679号