2
我想異步讀取Arduino的Android設備上的繩子,使用這裏安卓讀取USB異步
https://github.com/mik3y/usb-serial-for-android
下載庫我設法做到這一點,但代碼工作只有一次,而不是在一個循環中。 我試過在asyncTask中執行它,但程序崩潰,所以我設法通過在循環中執行runnable來執行循環,但程序每次執行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}
我構造的可運行要執行這樣說:
@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}
}
};
希望能幫到你!