gpt4 book ai didi

java - android异步读取usb

转载 作者:行者123 更新时间:2023-11-30 11:24:31 24 4
gpt4 key购买 nike

我正在尝试使用此处下载的库从 Android 设备上的 Arduino 异步读取字符串

https://github.com/mik3y/usb-serial-for-android

我设法做到了,但代码只工作一次,而不是在一个循环周期中。我曾尝试在 asyncTask 中执行此操作,但程序崩溃了,因此我设法通过在循环中执行可运行来完成循环,但每次执行可运行时程序都会卡住,并在可运行结束工作时取消卡住。

这是用于从 USB 读取的代码:

try
{
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
driver = UsbSerialProber.acquire(manager);
if (driver != null) {

driver.open();
driver.setBaudRate(9600);
new Thread(runnable).start();
buffer = new byte[3000];
numBytesRead = driver.read(buffer, 3000);
String str = new String(buffer, "UTF-8");
buffer = null;
numBytesRead = 0;
}
}
catch(Exception ex){//do nothing}

我将 runnable 构造为以这种方式执行:

@Override
protected void onCreate(Bundle savedInstanceState) {
try
{
UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
driver = UsbSerialProber.acquire(manager);
if (driver != null) {

driver.open();
driver.setBaudRate(9600);
handler.postDelayed(runnable, 1);
}
}
catch(Exception ex){//do nothing}
}



private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
buffer = new byte[3000];
numBytesRead = driver.read(buffer, 3000);
String str = new String(buffer, "UTF-8");
buffer = null;
numBytesRead = 0;
handler.postDelayed(this, 1); //here is where the runnable is executed again. This generates the loop
}
catch (IOException e) {//do nothing}
}
};

希望你能帮上忙!

最佳答案

解决了!

我改变了参数1在

handler.postDelayed(runnable, 1);

handler.postDelayed(this, 1);

handler.postDelayed(runnable, 0);
handler.postDelayed(this, 0);

我还在这里更改了缓冲区大小:

buffer = new byte[3000];
numBytesRead = driver.read(buffer, 3000);

从 3000 到 40,这就是程序这么慢的原因。

还是谢谢你!

关于java - android异步读取usb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20630951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com