# 监听USB设备的插拔，请求USB设备权限，获取当前连接的所有USB设备

#### 定制或采购源码联系QQ252797991

1. 下载demo，拷贝demo里的AndroidManifest.xml文件到uniapp项目根目录下
2. 点击插件页面右上角的"试用"按钮，按照提示集成到uniapp项目
3. 删除本地基座和手机app
4. 重新自定义基座运行

```

	import {
		UTSUsbManager,
	} from "@/uni_modules/wrs-uts-usbmanager";


```

- 监听USB设备的插拔

```

				// 注册USB插拔监听
				UTSUsbManager.registerReceiver(this.action, (resp) => {
					let action = resp.action;
					switch (action) {
						// USB授权结果
						case this.action: {
							let granted = resp.granted
							let action = resp.action
							let device = resp.device
							this.showMsg("有USB设备授权结果:" + JSON.stringify(resp));
							if (granted) {
								this.showMsg("有USB设备授权成功");
							} else {
								this.showMsg("有USB设备授权失败");
							}
						}
						break;
						// 监测到有USB拔出
						case "android.hardware.usb.action.USB_DEVICE_DETACHED": {
							this.showMsg("有USB设备拔出:" + JSON.stringify(resp));
						}
						break;
						// 检测到有USB插入
						case "android.hardware.usb.action.USB_DEVICE_ATTACHED": {
							// USB插入时，有些设备会监听到USB插入-USB设备拔出-USB设备插入这么个过程，可能是系统或USB设备的bug
							this.showMsg("有USB设备插入:" + JSON.stringify(resp));
						}
						break;
						default:
							break;
					}
				})

```

- 取消监听USB设备的插拔

```

UTSUsbManager.unregisterReceiver()

```

- 获取当前连接的所有USB设备


```

		UTSUsbManager.getDeviceList((resp) => {
						this.showMsg(JSON.stringify(resp))
						// {"devices":[{"deviceName":"/dev/bus/usb/001/017","interfaceCount":2,"interfaces":[{"id":0,"name":"Espressif CDC Device","interfaceProtocol":0,"interfaceClass":2},{"id":1,"interfaceProtocol":0,"interfaceClass":10}],"deviceId":1017,"deviceProtocol":0}]}
				});

```

- 请求某个USB设备权限

权限结果在registerReceiver里回调

```

let device = devices[index];
							let deviceId = device.deviceId;
							let requestCode = this.requestCode;
							let action = this.action;
							let flags = 0;
							
							UTSUsbManager.requestPermission(deviceId, requestCode, action, flags);

```