2017-06-03 175 views
0

這是來自Google示例代碼BluetoothChat的Standard的一段代碼。 BluetoothChatService.java無法連接到藍牙設備

public void run() { 
     Log.i(TAG, "BEGIN mConnectedThread"); 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (mState == STATE_CONNECTED) { 
      try { 
       // Read from the InputStream 
       bytes = mmInStream.read(buffer); 
       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
      } catch (IOException e) { 
       Log.e(TAG, "disconnected", e); 
       connectionLost(); 
       break; 
      } 
     } 
    } 

當我嘗試使用

mChatService.connect(device, false); 

設備連接我得到異常

java.io.IOException: bt socket closed, read return: -1 
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872) 
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96) 
at java.io.InputStream.read(InputStream.java:163) 

任何幫助,將不勝感激以下。

+0

根據日誌,bt連接嘗試失敗。所以你可以嘗試系統藍牙連接你的設備。設備是否需要配對? –

+0

設備已經配對。 – Nikki

回答

0

您是否在Android清單中包含您的應用的藍牙許可?

<uses-permission android:name="android.permission.BLUETOOTH" /> 
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> 
+0

是的。我已經在清單中包含了上述權限。 – Nikki

0

我想這個問題是mmSocket.connect()

嘗試獲得通過反映方法createRfcommSocket

以下是Google示例代碼BluetoothChat的示例基礎。

  // Make a connection to the BluetoothSocket 
      try { 
       Thread.sleep(500); 
       // This is a blocking call and will only return on a 
       // successful connection or an exception 
       mmSocket.connect(); 
       OutputStream os = mmSocket.getOutputStream(); 
       // Here: connect success 
      } catch (Exception e) { 
       Log.i(TAG, "Lost 1st try; SPP connect[2]"); 
       try { 
        mmSocket.close();// close the current socket 
        mmSocket = null; 
        Thread.sleep(500L); // wait for a while 
        mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1); // The key method ! 
        mmSocket.connect(); 
        OutputStream os = mmSocket.getOutputStream(); 
        // Here: connect success 
        synchronized (ESDevice.this) { 
         mSPPConnectThread = null; 
        } 
        connected(mmSocket, mmDevice); // begin connected thread 
       } catch (Exception e2) { 
        Log.e(TAG, "Lost 2nd try. Connect fail", e2); 
        connectionFailed(); 
        return; 
       } 
       return; 
      } 
0

它看起來就像你在mConnectedThread的構造函數傳遞之前,套接字被關閉。

還有就是谷歌樣品中一個棘手的事情,在當插座竟是連接mConnectThread我們做mConnectThread空,下面的代碼不會被執行:

if (mConnectThread != null) { 
    mConnectThread.cancel(); 
    mConnectThread = null; 
} 

這意味着cancel()方法,該方法關閉套接字將被跳過。

基本上,確保在套接字連接後,請勿在ConnectThread中調用close()方法。