2012-01-28 48 views
0

正如標題所解釋的,我很難通過藍牙向我的PC發送一些數據。我試圖建立與我的android手機作爲客戶端和我的PC作爲服務器的連接。當我嘗試通過BluetoothSocket.connect()建立連接時,我的手機會提示輸入PIN碼。輸入後,我的電腦也會提示輸入相同的引腳,但在輸入之前,connect()方法會拋出IOException異常。我假設connect() - 方法在我能夠在PC上輸入正確的引腳之前超時,但是如何才能讓它等待足夠長的時間以輸入PIN?Android配對不起作用 - 「通過對端重置連接」

編輯:重新配對PC後,我的手機它的工作,因爲配對對話框不會出現在我的應用了。如果我取消配對PC並啓動我的應用程序,配對對話框彈出,但在幾秒鐘後消失,並且套接字引發異常(「通過對等方重置連接」)。顯然連接在配對完成之前重置,但爲什麼?

這裏是我的代碼:

private void connectToDevice(BluetoothDevice device) 
{ 
    mBluetoothAdapter.cancelDiscovery(); 
    BluetoothSocket socket = null; 
    try 
    { 
     socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-      0000- 1000-8000-00805F9B34FB")); 
    } 
    catch (IOException e) 
    { 
     Log.e("HeliRemote", "Couldn't get socket."); 
     return; 
    } 
    try 
    { 
     socket.connect(); 
    } 
    catch (IOException e) 
    { 
     try 
     { 
      socket.close(); 
     } 
     catch (IOException e1) 
     { 
      Log.e("HeliRemote", "Couldn't close connection"); 
     } 
     // That's the message I get in LogCat 
     Log.e("HeliRemote", "Couldn't connect to Socket."); 
     return; 
    } 

    Log.i("HeliRemote", "connected."); 
} 

我會很高興,如果有人可以給我建議的關於該問題的任何好話。

回答

1
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}); 
     mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothDevice, 1); 


     // mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID); 
     mBluetoothAdapter.cancelDiscovery(); 

     mBluetoothSocket.connect(); 





    } 
    catch (IOException eConnectException) 
    { 
     Log.d(TAG, "CouldNotConnectToSocket", eConnectException); 
     closeSocket(mBluetoothSocket); 
     return; 
    } catch (SecurityException e) { 

     Log.d(TAG, "CouldNotConnectToSocket", e); 
     closeSocket(mBluetoothSocket); 
    } catch (NoSuchMethodException e) { 

     Log.d(TAG, "CouldNotConnectToSocket", e); 
     closeSocket(mBluetoothSocket); 
    } catch (IllegalArgumentException e) { 
     Log.d(TAG, "CouldNotConnectToSocket", e); 
     closeSocket(mBluetoothSocket); 
    } catch (IllegalAccessException e) { 
     Log.d(TAG, "CouldNotConnectToSocket", e); 
     closeSocket(mBluetoothSocket); 
    } catch (InvocationTargetException e) { 
     Log.d(TAG, "CouldNotConnectToSocket", e); 
     closeSocket(mBluetoothSocket); 
    } 
} 

試試這個...

相關問題