2016-06-19 8 views
0

私はArduino HC-06 Bluetoothとデータを交換する必要があるアプリケーションを作成しています。ここでは、データ交換方法は次のとおりです。AndroidのBluetoothの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) 

助けてください、私は多くのソリューションを試みたし、彼らが働いていません。

答えて

0

Handlerではなく、ワーカースレッドからUIにデータを送信しています。runOnUiThreadを編集して使用してください。

handler.post(new Runnable() 
{ 
    public void run() 
    { 
     myLabel1.setText(data); 
    } 
}); 

使用この:代わりの

答えを

runOnUiThread(new Runnable(){ 
    public void run() { 
     myLabel1.setText(data); 
    } 
}); 
+0

感謝.. エラーがなくなっているが、このアプリは、受信したデータのために対応されていません...? –

+0

私はあなたの現在の問題を本当に理解していません。 「アプリが受信したデータに応答していない」とはどういう意味ですか? –

+0

私はarduinoからのBluetooth受信データがLabelに表示されていないことを意味します。 –

関連する問題