2013-06-18 66 views
0

我對android和java很陌生,所以要溫柔:) 我試圖通過blototh連接兩部手機。 我讓兩部手機都通過創建serversocket來監聽來電,然後從一部手機(作爲客戶端)初始化連接。有趣的是,當我試圖讓我的LG(Android版本2.3.4)連接宏達電(Android 2.2.1)一切工作正常,但是當我嘗試使HTc手機作爲客戶端連接我沒有得到任何結果。調試器顯示HTC在mmSocket.connect()失敗。並執行catch(IOException connectException)。我的代碼基本上是從Android藍牙教程複製/粘貼。任何建議爲什麼手機行爲不同?連接螺紋:藍牙只能使用一種方式

private class ConnectThread extends Thread { 
    private final BluetoothSocket mmSocket; 
    private final BluetoothDevice mmDevice; 

    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 
     BtAdapter.cancelDiscovery(); 
     try { 
      // Connect the device through the socket. This will block 
      // until it succeeds or throws an exception 
      mmSocket.connect(); **HTC phones fails here and goes to CATCH block** 
      // make info message 
      Message msg = mainHandler.obtainMessage(); 
      Bundle bundle = new Bundle(); 
      String btnTxt = "Connected"; 
      bundle.putString("myKey", btnTxt); 
      msg.setData(bundle); 
      mainHandler.sendMessage(msg); 
     } catch (IOException connectException) { 
      // Unable to connect; close the socket and get out 
      try { 
       mmSocket.close(); 
      } catch (IOException closeException) { } 
      return; 
     } 
     // Do work to manage the connection (in a separate thread) 
     ConnectedThread conThread = new ConnectedThread(mmSocket); 
     conThread.start(); 
    } 

    /** Will cancel an in-progress connection, and close the socket */ 
    public void cancel() { 
     try { 
      mmSocket.close(); 
     } catch (IOException e) { } 
    } 
} 

回答

0

可能有問題與

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

你的HTC 2.21的設備上。檢查HTC設備的Bluetoth適配器支持哪些功能,這可能與您的程序出現故障的原因有關。

「使用此接口只有通過身份驗證的插座連接是可能的。 認證是指鏈路密鑰的驗證,防止 人在這方面的中間人類型的攻擊。例如,對於藍牙2.1 設備,如果任何設備沒有輸入和輸出功能或者只能顯示數字鍵,則不能使用套接字連接,在這種情況下,請使用{#link createInsecureRfcommSocketToServiceRecord}。更多詳細信息,請參閱 「藍牙核心規範 版本2.1 + EDR」的安全模型部分5.2(第3卷)。「

http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createRfcommSocketToServiceRecord%28java.util.UUID%29