Android N Method for obtaining the path of external SD card or mounting U disk
- 2021-10-11 19:31:37
- OfStack
There is no direct way to get the external SD card or mount the U disk path on Android N. You can get the internal sd card path by the following method
Environment.getExternalStorageDirectory().getAbsolutePath();
By looking at the source code of getExternalStorageDirectory, it is found that Android is only obtained without an exposed interface
public static File getExternalStorageDirectory() {
throwIfUserRequired();
return sCurrentUser.getExternalDirs()[0];
}
Built-in sd card takes the first value in sCurrentUser. getExternalDirs (). By looking at the public method of StorageManager, all StorageVolume can be obtained by sending StorageManager @ getStorageVolumes, but only one simple method can be called through StorageVolume object, and it is found that StorageVolume has many hidden methods as follows:
frameworks/base/core/java/android/os/storage/StorageVolume.java
/**
* Returns true if the volume is removable.
*
* @return is removable
*/
public boolean isRemovable() {
return mRemovable;
}
/**
* Returns the mount path for the volume.
*
* @return the mount path
* @hide
*/
public String getPath() {
return mPath.toString();
}
/** {@hide} */
public File getPathFile() {
return mPath;
}
If there is no exposed interface to call these methods, you can only think of reflection. The specific implementation is as follows:
1. Add the required permissions in the cleared AndroidManifest. xml file
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
2. Obtain the path of external SD card or mount U disk through reflection
private StorageManager mStorageManager;
mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
// Get all mounted devices (internal sd Card, external sd Card, mounted U Disk)
List<StorageVolume> volumes = mStorageManager.getStorageVolumes();
try {
Class<?> storageVolumeClazz = Class
.forName("android.os.storage.StorageVolume");
// Call the system through reflection hide Method of
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
for (int i = 0; i < volumes.size(); i++) {
StorageVolume storageVolume = volumes.get(i);// Gets each mounted StorageVolume
// Called by reflection getPath , isRemovable
String storagePath = (String) getPath.invoke(storageVolume); // Get the path
boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);// Removable or not
String description = storageVolume.getDescription(this);
Log.d("jason", " i=" + i + " ,storagePath=" + storagePath
+ " ,isRemovableResult=" + isRemovableResult +" ,description="+description);
}
} catch (Exception e) {
Log.d("jason", " e:" + e);
}