0
我在寫一個需要與Arduino HC-06藍牙交換數據的應用程序。下面是數據交換方法:Android中的藍牙錯誤InputStream
void ListenForBluetoothData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
if(BTinStream!=null)
{
int bytesAvailable = BTinStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
BTinStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel1.setText(data);
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
}else {
continue;
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
,我收到的主要錯誤是:
06-19 11:21:23.011 17542-17910/com.example.farok.bluetoothcommunicationarduino E/AndroidRuntime: FATAL EXCEPTION: Thread-41375
Process: com.example.farok.bluetoothcommunicationarduino, PID: 17542
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at com.example.farok.bluetoothcommunicationarduino.MainActivity.ListenForBluetoothData(MainActivity.java:179)
at com.example.farok.bluetoothcommunicationarduino.MainActivity$1.run(MainActivity.java:69)
請幫幫忙,我已經嘗試了許多解決方案,他們都沒有奏效。
感謝答案.. 的錯誤消失,但應用程序未對接收的數據作出反應..? –
我不太瞭解你目前的問題。您的意思是「該應用程序對接收的數據沒有響應」? –
我的意思是藍牙接收到的數據來自arduino沒有顯示在標籤中。 –