我使用动态广播可以接收UsbManager.ACTION_USB_DEVICE_ATTACHED
和UsbManager.ACTION_USB_DEVICE_DETACHED
事件。
但是当我的应用未运行时,USB设备已插入,动态广播无法接收到它。因此,我想在我的应用首次运行时进行检查。
我使用静态广播可以接收事件,但是我不想使用该方法,是否还有其他方法?
答案 0 :(得分:1)
您可以使用UsbManager
类并获取已连接设备的列表,请尝试使用以下方法并在onCreate
中调用它
private void findSerialPortDevice() {
// This snippet will try to open the first encountered usb device connected, excluding usb root hubs
UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
int devicePID = device.getProductId();
intf = device.getInterface(0);
if(device != null && !device.equals(""))
Utils.writeIntoFile(getBaseContext(),"device =============>"+device+"\n"+"getInterface Count =============>"+device.getInterfaceCount());
// There is a device connected to our Android device. Try to open it as a Serial Port.
} else {
connection = null;
device = null;
}
}
if (!keep)
break;
}
if (!keep) {
// There is no USB devices connected.
}
} else {
// There is no USB devices connected.
}
}
答案 1 :(得分:1)
如果要在连接设备后启动应用,则必须在清单中注册USB设备的VID / PID
<activity
android:name="..."
...>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<meta-data
android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>
和device_filter.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 0x0403 / 0x6001: FTDI FT232R UART -->
<usb-device vendor-id="1027" product-id="24577" />
...
例如如here