如何获得可移动存储/ SD卡的路径?以及最新的/ storage / ???? ????格式

问题描述

如何在Android 10(尤其是三星手机)上获得可移动存储(可移动SD卡)的路径。 由于可移动存储的位置现在为/ storage / ????格式。 ???? 我发现,随着每部手机的变化,路径很难获取

我也在发布该解决方案,该解决方案在三星和Mi手机上运行良好。

解决方法

在每部电话或仿真器上,您使用第二个返回的项获得指向可移动Micro SD卡上应用程序特定文件夹的路径

getExternalFilesDirs()

每个使用的微型SD卡的路径都不相同。

,

我想分享一个解决方案,该解决方案花了我几天的时间来寻找,希望也能对其他人有所帮助。最新android版本上的可移动sd卡存储类似于“ / storage / ???? ????”,此位置很难获得。 I found the following code from here: 即使在三星手机上,此代码也有助于获得正确的位置。我已经在三星和小米手机上尝试过。

/**
  • 使用反射获取外部SD卡路径

  • @param mContext

  • @param is_removable是否可移动外部存储

  • @return * /

     private static String getExternalStoragePath(Context mContext,boolean is_removable) {
    
     StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
     Class<?> storageVolumeClazz = null;
     try {
         storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
         Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
         Method getPath = storageVolumeClazz.getMethod("getPath");
         Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
         Object result = getVolumeList.invoke(mStorageManager);
         final int length = Array.getLength(result);
         for (int i = 0; i < length; i++) {
             Object storageVolumeElement = Array.get(result,i);
             String path = (String) getPath.invoke(storageVolumeElement);
             boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
             if (is_removable == removable) {
                 return path;
             }
         }
     } catch (ClassNotFoundException e) {
         e.printStackTrace();
     } catch (InvocationTargetException e) {
         e.printStackTrace();
     } catch (NoSuchMethodException e) {
         e.printStackTrace();
     } catch (IllegalAccessException e) {
         e.printStackTrace();
     }
     return null;
    

    }