2016-03-24 82 views
1

我正在開發一個處理使用Arduino製作的報警系統的Android應用程序。 我必須處理從Arduino和OutputStream到Arduino的InputStream。首先,我使用線程來初始化藍牙套接字的連接並且它可以工作,但是在線程內部,我必須調用某種服務/線程,這可以讓我處理來自Arduino的數據流,但我不知道如何做到這一點。 事實是,假設的服務必須連續聽,如果有流,它必須停止,只有當我想要,而不是一段時間後。謝謝您的幫助!下面是與藍牙套接字連接代碼:如何在Android中通過藍牙處理InputStream和OutputStream

public class ConnectThread extends Thread { 
    private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 
    private final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 

    public ConnectThread(BluetoothDevice device) { 
     // Use a temporary object that is later assigned to mmSocket, 
     // because mmSocket is final 
     BluetoothSocket tmp = null; 
     mmDevice = device; 

     // Get a BluetoothSocket to connect with the given BluetoothDevice 
     try { 
      // MY_UUID is the app's UUID string, also used by the server code 
      tmp = device.createRfcommSocketToServiceRecord(MY_UUID); 
     } catch (IOException e) { } 
     mmSocket = tmp; 
    } 

    public void run() { 
     // Cancel discovery because it will slow down the connection 
     while (!Thread.currentThread().isInterrupted()) { 
      mBluetoothAdapter.cancelDiscovery(); 

      try { 
       // Connect the device through the socket. This will block 
       // until it succeeds or throws an exception 
       mmSocket.connect(); 
      } catch (IOException connectException) { 
       // Unable to connect; close the socket and get out 
       try { 
        mmSocket.close(); 
        Log.i("Log", "Socket closed"); 
        this.interrupt(); 
        Log.i("Log", "Thread interrupted"); 
       } catch (IOException closeException) { 

       } 
      } 

      //I think here I have to start a sort of Service/Thread.. 
     } 
    } 
    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
      this.interrupt(); 
      Log.i("Log", "Thread interrupted"); 
     } catch (IOException e) { } 
    } 
} 

回答

0

我實現了一個類似的算法,我基本上是從BluetoothChatSample複製,即例如內建Android工作室樣了。

你可以看到所有的概念,如何接收,以樣本中發送一個字符串,他們已經添加權限,對話框詢問有關啓用藍牙和這樣的用戶了。