Android中,第三方app获取设备挂载的U盘路径的方法有哪些?给出java代码,Android8.0以上
时间: 2024-04-29 15:21:01 浏览: 116
1. 使用StorageManager获取U盘路径
```
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
List<VolumeInfo> volumes = storageManager.getVolumes();
for (VolumeInfo volume : volumes) {
if (volume.getType() == VolumeInfo.TYPE_PUBLIC && volume.getState() == VolumeInfo.STATE_MOUNTED) {
File uDiskFile = volume.getPath();
Log.d(TAG, "U盘路径:" + uDiskFile.getAbsolutePath());
}
}
```
2. 使用UsbManager获取U盘路径
```
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
Iterator<UsbDevice> iterator = deviceList.values().iterator();
while (iterator.hasNext()) {
UsbDevice usbDevice = iterator.next();
if (usbDevice.getVendorId() == VENDOR_ID && usbDevice.getProductId() == PRODUCT_ID) {
String path = null;
for (int i = 0; i < usbDevice.getInterfaceCount(); i++) {
UsbInterface usbInterface = usbDevice.getInterface(i);
if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_MASS_STORAGE
&& usbInterface.getInterfaceSubclass() == INTERFACE_SUBCLASS
&& usbInterface.getInterfaceProtocol() == INTERFACE_PROTOCOL) {
UsbEndpoint endpoint = usbInterface.getEndpoint(0);
UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
if (connection != null && connection.claimInterface(usbInterface, true)) {
byte[] buffer = new byte[MAX_BUFFER_SIZE];
int result = connection.bulkTransfer(endpoint, buffer, buffer.length, BULK_TRANSFER_TIMEOUT_MS);
if (result > 0) {
path = new String(buffer, 0, result);
Log.d(TAG, "U盘路径:" + path);
break;
}
}
}
}
if (path != null) {
break;
}
}
}
```
注意:需要在AndroidManifest.xml中添加以下权限
```
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.USB_PERMISSION" />
```
阅读全文