Android 6.0 之后提供了StorageManager支持读写U盘。有部分是hide方法需要利用下反射,以下记录下。
读取U盘
public static List<UsbDevice> readUsbDevice(Context context) {
List<UsbDevice> devices = new ArrayList<>();
try {
StorageManager storageManager = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
Method volumeListMethod = StorageManager.class.getMethod("getVolumeList");
volumeListMethod.setAccessible(true);
Method pathMethod = StorageVolume.class.getMethod("getPath");
pathMethod.setAccessible(true);
StorageVolume[] volumeList = (StorageVolume[]) volumeListMethod.invoke(storageManager);
if (volumeList == null) {
return devices;
}
// 去除本地目录
String localPath = Environment.getExternalStorageDirectory().getAbsolutePath();
for (StorageVolume volume: volumeList) {
String description = volume.getDescription(context);
String path = (String) pathMethod.invoke(volume);
if (!volume.isRemovable() && !TextUtils.equals(localPath, path)) {
devices.add(new UsbDevice(description, path));
}
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return devices;
}
写入U盘文件
上面的UsbDevice已经拿到了Usb的路径path,以下就如同操作文件夹一样写入文件就ok了
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/app/6266.html