我正在尝试使用此处下载的库异步读取Android设备上的Arduino字符串
https://github.com/mik3y/usb-serial-for-android
我设法做到了,但代码只工作一次而不是循环周期。 我已经尝试在asyncTask中执行但是程序崩溃了,所以我设法通过执行runnable in循环来执行循环,但程序在每次执行runnable时冻结,并在runnable结束工作时取消冻结。
这是用于从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}
}
};
希望你能帮忙!
答案 0 :(得分:1)
解决!
我在
中更改了参数1handler.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,这就是程序如此缓慢的原因。
无论如何,谢谢!