我需要使用 USB 条形码扫描仪读取条形码,扫描仪配置为我们 USB Hid。对于通信,我使用https://github.com/benlypan/UsbHid 阅读有效,但问题是如果我连接到设备应用程序被阻止。与设备的连接是在 Thread 中建立的,但无论如何它都会阻塞。线程在服务中运行。
我解决了这样的问题
try
{
byte[] readBuffer = device.read(64, 100);
String data = new String(readBuffer, StandardCharsets.UTF_8);
//Only messages start with 0x02
if(readBuffer[0] == 0x02) {
String barcode = data.substring(2, getZeroPosition(readBuffer) + 1);
Log.e("TAG", barcode);
//Read util end otherwise
while (getZeroPosition(readBuffer) != 0) {
try {
readBuffer = device.read(64, 100);
data = new String(readBuffer, StandardCharsets.UTF_8);
barcode += data.substring(0, getZeroPosition(readBuffer) + 1);
} catch (Exception e) {
break;
}
}
}
catch (Exception e) {}
在后台图书馆使用
android.hardware.usb.UsbDeviceConnection.bulkTransfer
我尝试阅读,如果遇到超时,我会等待 1000 毫秒并再次阅读,这是可行的,但我认为应该有可能以更好的方式做到这一点。
有没有办法在不阻塞整个应用程序的情况下阅读?
谢谢