import android.content.Context; import android.os.storage.StorageManager; import java.lang.reflect.Method; public class USBUtil { public static String getUSBPath(Context context) { StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE); try { // 通过反射调用getVolumeList,获取所有挂载的设备(内部sd卡、外部sd卡、挂载的U盘) Method getVolumeListMethod = StorageManager.class.getMethod("getVolumeList"); Object[] volumes = (Object[]) getVolumeListMethod.invoke(storageManager); Class<?> storageVolumeClazz = Class.forName("android.os.storage.StorageVolume"); // 通过反射调用getPath、isRemovable Method getPathMethod = storageVolumeClazz.getMethod("getPath"); Method isRemovableMethod = storageVolumeClazz.getMethod("isRemovable"); if (volumes != null && volumes.length > 0) { for (Object volume : volumes) { String path = (String) getPathMethod.invoke(volume); // 获取路径 boolean isRemovable = (boolean) isRemovableMethod.invoke(volume);// 是否可移除 if (isRemovable) { return path; } } } } catch (Exception e) { e.printStackTrace(); } return "/"; } }
参考链接:
获取Android设备上的所有存储设备