SoFunction
Updated on 2025-04-07

How to get and distinguish sdcard and USB paths on Android 6.0

On Android 6.0, the mount path will be generated dynamically based on the type of card and the mount status of the card. Therefore, the method of writing a fixed path before is unavailable. Finally, the android source code is searched and analyzed online, and the path is obtained through reflection, and the code is correct. The code is as follows:

/**
   * 6.0 gets the external sdcard and USB disk paths and distinguishes them
   * @param mContext
   * @param keyword SD = "Internal Storage"; EXT = "SD Card"; USB = "U disk"
   * @return
   */
 public static String getStoragePath(Context mContext,String keyword) {
  String targetpath = "";
  StorageManager mStorageManager = (StorageManager) mContext
    .getSystemService(Context.STORAGE_SERVICE);
  Class<?> storageVolumeClazz = null;
  try {
   storageVolumeClazz = ("");
   
   Method getVolumeList = ().getMethod("getVolumeList");
   
   Method getPath = ("getPath");
     
   Object result = (mStorageManager);
   
   final int length = (result);
   
   Method getUserLabel = ("getUserLabel");
   
   
   for (int i = 0; i < length; i++) {
    
    Object storageVolumeElement = (result, i);
    
    String userLabel = (String) (storageVolumeElement);
    
    String path = (String) (storageVolumeElement);
    
    if((keyword)){
     targetpath = path;
    }

   }
  } catch (ClassNotFoundException e) {
   ();
  } catch (InvocationTargetException e) {
   ();
  } catch (NoSuchMethodException e) {
   ();
  } catch (IllegalAccessException e) {
   ();
  }
  return targetpath ;
 }

The userLabel obtained here is a label given to each disk by the system, which is used to distinguish whether it is internal storage, sdcard or USB disk. The label of the inner card is fixed, but the label of the sdcard and USB disk are dynamically generated based on type, status and other information, so "if((keyword)){" here does not use equals.

Summary: Don't understand the source code

The above article on Android 6.0 is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.