2015-04-16 61 views
1

我是絕對的初學者。目前,我試圖製作一個應用程序,通過藍牙將輸出數據發送到arduino。爲此,我創建了一個類如下。在主UI線程中實現runnable類的方法中設置計時器

private class SendReceiveBytes implements Runnable { 
    private BluetoothSocket btSocket; 
    private InputStream inputStream; 
    private OutputStream outputStream; 
    String TAG = "SendReceiveBytes"; 

    public SendReceiveBytes(BluetoothSocket socket) { 
     btSocket = socket; 
     try { 
      inputStream = btSocket.getInputStream(); 
      outputStream = btSocket.getOutputStream(); 
     } 
     catch (IOException streamError) { 
      Log.e(TAG, "Error when getting input or output Stream"); 
     } 
    } 

    @Override 
    public void run() { 
     // buffer store for the stream. 
     byte[] buffer = new byte[1024]; 
     // bytes returned from the stream. 
     int bytes; 

     // Keep listening to the InputStream until an exception occurs 
     while (true) { 
      try { 
       // Read from the InputStream 
       bytes = inputStream.read(buffer); 
       // Send the obtained bytes to the UI activity 
       socketHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 
      } 
      catch (IOException e) { 
       Log.e(TAG, "Error reading from inputStream"); 
       break; 
      } 
     } 
    } 

    /* Call this from the main activity to send data to the remote device */ 
    public void write(String outputData) { 
     try { 
      outputStream.write(outputData.getBytes(Charset.forName("UTF-8"))); 
     } 
     catch (IOException e) { 
      Log.e(TAG, "Error when writing to outputStream"); 
     } 
    } 

    /* Call this from the main activity to shutdown the connection */ 
    public void cancel() { 
     try { 
      btSocket.close(); 
     } 
     catch (IOException e) { 
      Log.e(TAG, "Error when closing the btSocket"); 
     } 
    } 
} 

在我的OnCreate()方法中,我按如下操作。

final SendReceiveBytes sendBytes = new SendReceiveBytes(bluetoothSocket); 
final Handler moveHandler = new Handler(); 
View.OnLongClickListener longClickListener = new View.OnLongClickListener() { 
     public boolean onLongClick(View view) { 
      switch (view.getId()) { 
       case R.id.driveFwd: 
        moveHandler.postDelayed(sendBytes.write("MOVE_FORWARD"), 250); 
        sendBytes.write("MOVE_FORWARD"); 
        break; 

我現在遇到的問題是調用方法write()的正確過程。什麼是正確的方式繼續下去?

回答

相關問題