connection.getFileDescriptor()是int,没有valid方法
时间: 2024-02-27 12:54:40 浏览: 23
非常抱歉,我的回答有误。在 Android 中,UsbDeviceConnection 类的 `getFileDescriptor()` 方法返回的是 `FileDescriptor` 类型的对象,而非 `int` 类型的对象。同时,`FileDescriptor` 类确实没有 `valid()` 方法。
正确的做法是,在获取 `FileDescriptor` 对象后,可以使用 `FileOutputStream` 类的 `getFD()` 方法获取一个 `FileDescriptor` 对象。然后,判断这两个对象是否相等即可判断连接是否有效。具体的步骤如下:
1. 获取 USBManager 对象:通过 getSystemService() 方法获取系统服务 USB_SERVICE,然后强制转换为 USBManager 类型。
2. 获取 USB 设备列表:使用 getDeviceList() 方法获取当前连接的 USB 设备列表。
3. 连接 USB 设备:对于需要使用的 USB 设备,可以使用 USBManager 类中的 `openDevice()` 方法来获取与设备的连接。该方法接收一个 `UsbDevice` 对象作为参数,返回一个 `UsbDeviceConnection` 对象。
4. 判断 USB 设备状态:对于每个 USB 设备,可以使用 `UsbDeviceConnection` 对象中的 `getFileDescriptor()` 方法获取与设备的连接,然后使用 `FileOutputStream` 类中的 `getFD()` 方法获取一个 `FileDescriptor` 对象。然后,判断这两个对象是否相等即可判断连接是否有效。如果连接有效,则设备处于已连接状态;否则设备处于已断开状态。
下面是示例代码:
```java
// 获取 USBManager 对象
USBManager usbManager = (USBManager) getSystemService(Context.USB_SERVICE);
// 获取 USB 设备列表
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
// 遍历 USB 设备列表
for (UsbDevice device : deviceList.values()) {
// 连接 USB 设备
UsbDeviceConnection connection = usbManager.openDevice(device);
// 判断设备状态
if (connection != null && connection.getFileDescriptor() != null) {
// 获取连接的 FileDescriptor 对象
FileDescriptor fd = connection.getFileDescriptor();
// 获取 FileDescriptor 对象的副本
FileDescriptor fdCopy = new FileOutputStream(fd).getFD();
// 判断连接是否有效
if (fd == fdCopy) {
// 设备已连接
} else {
// 设备已断开
}
} else {
// 设备已断开
}
// 断开与 USB 设备的连接
connection.close();
}
```
需要注意的是,连接 USB 设备需要在具有 USB 设备权限的情况下进行,否则将无法连接到设备。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)