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没有显示在标签中。 –