2012-10-24 41 views
3

我正在通過應用程序將客戶端藍牙設備與我的手機配對。現在,我正在使用asynctask中的以下代碼嘗試爲遠程設備創建一個套接字。在android中配對藍牙設備的正確順序是什麼?

try{ 
    ba.cancelDiscovery(); 
    socket= blud.createRfcommSocketToServiceRecord(uuid); 
    Method m = blud.getClass().getMethod("createRfcommSocket", new     
    Class[] {int.class}); 
    socket = (BluetoothSocket) m.invoke(blud, 1); 
}catch(Exception e){e.printStackTrace();} 

我不知道如果我需要沿着在那裏我有一個連接線程和接收線程,或者如果asynctasks是足夠的了BluetoothChat例子的線條更。

這是我使用的UUID字符串00001101-0000-1000-8000-00805F9B34FB 我操作的順序是我在服務器端偵聽,一旦我試圖打開藍牙設備的套接字我嘗試連接,但最終得到一個權限被拒絕IO異常

回答

0

您需要請求藍牙權限和BLUETOOTH_ADMIN許可,您的清單 被Android API的文件檔案化here

「注意:大多數方法需要藍牙權限有些還需要BLUETOOTH_ADMIN權限。「

+0

我有我的清單和互聯網權限 – KP44

+0

你在服務器端使用listenUsingInsecureRfcommWithServiceRecord或listenUsingRfcommWithServiceRecord嗎?還有一件事我能想到的是,你需要在服務器端打開發現模式一秒鐘(大約120〜300)。 –

+0

即時通訊使用listenusingrfcommwithservicerecord,但在同一個asynctask作爲我的createrfcommsockettoservicerecord和打開發現模式是有道理的,我會嘗試這謝謝你jconfus – KP44

0

藍牙權限,加入Android清單文件中的下列 -

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

要創建債券使用 -

public boolean createBond(BluetoothDevice btDevice) 
    throws Exception 
    { 
     Class class1 = Class.forName("android.bluetooth.BluetoothDevice"); 
     Method createBondMethod = class1.getMethod("createBond"); 
     Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice); 
     return returnValue.booleanValue(); 
    } 

要創建插座 -

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException { 
     if(Build.VERSION.SDK_INT >= 10){ 
      try { 
       final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class }); 
       return (BluetoothSocket) m.invoke(device, my_UUID); 
      } catch (Exception e) { 
       Log.e("No Connection Created", "Could not create Insecure RFComm Connection",e); 
      } 
     } 
     return device.createRfcommSocketToServiceRecord(my_UUID); 
    } 

還要檢查Bluetooth Adapter來自android開發人員文檔。