Method for obtaining and distinguishing sdcard and U disk paths on Android 6.0

  • 2021-10-11 19:31:14
  • OfStack

On Android6.0, the mounting path will be dynamically generated according to the type of card and the mounting state of the card, so the previous method of writing a fixed path is not available. Finally, through the online search and analysis of android source code, the path is obtained through reflection, and the correct distinction is made. The code is as follows:


/**
  * 6.0 Get external sdcard And U Disk path, and distinguish between 
  * @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 = Class.forName("android.os.storage.StorageVolume");
   
   Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
   
   Method getPath = storageVolumeClazz.getMethod("getPath");
     
   Object result = getVolumeList.invoke(mStorageManager);
   
   final int length = Array.getLength(result);
   
   Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");
   
   
   for (int i = 0; i < length; i++) {
    
    Object storageVolumeElement = Array.get(result, i);
    
    String userLabel = (String) getUserLabel.invoke(storageVolumeElement);
    
    String path = (String) getPath.invoke(storageVolumeElement);
    
    if(userLabel.contains(keyword)){
     targetpath = path;
    }

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

The userLabel obtained here is an label given to each disk by the system, which is used to distinguish whether it is internal storage, sdcard or U disk. The label of the internal card is fixed, but the label of sdcard and U disks are dynamically generated according to information such as type and status, so equals is not used in "if (userLabel. contains (keyword) {".

Summary: I don't know how to look at the source code


Related articles: