2016-05-12 77 views
0

我試圖在我的應用程序開始時對串行藍牙設備進行簡單的連接序列。現在,這一切都是內部onCreate()失敗的藍牙序列

BT = BluetoothAdapter.getDefaultAdapter(); 

    BT.enable(); 
    if(!BT.isEnabled()) { 
     Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
     startActivityForResult(enabler, REQUEST_ENABLE); 
     BT.enable(); 
     Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show(); 
     //finish apk 
     finish(); 
    } 
    else { 
     Toast.makeText(getApplicationContext(), "Bluetooth On.", Toast.LENGTH_LONG).show(); 
    } 

    pairedDevices = BT.getBondedDevices(); 
    pDevices = new ArrayList<BluetoothDevice>(); 

    if (pairedDevices.size()>0) { 
     for(BluetoothDevice bt : pairedDevices) 
     { 
      pDevices.add(bt); //Get the device's name and the address 
     } 
    } 
    else { 
     Toast.makeText(getApplicationContext(), "Nothing paired.", Toast.LENGTH_LONG).show(); 
    } 

    try { 
     BluetoothDevice dispositivo = BT.getRemoteDevice(pDevices.get(0).getAddress()); 
     btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID); 
     btSocket.connect(); 
    } 
    catch (IOException e){ 
     Toast.makeText(getApplicationContext(), "Failed.", Toast.LENGTH_LONG).show(); 
    } 

的目標是連接到第一個可用的配對設備。到目前爲止,它總是顯示「失敗」。即使我在手機旁邊安裝了未連接的配對設備。

我應該在應用程序的其他地方做這個嗎?我不是真的擔心延遲主要活動,因爲這是個人項目。

編輯:拼寫

回答

0

所有BT 2.1設備和較新的要求安全連接,因此使用createRfcommSocketToServiceRecord代替createInsecureRfcommSocketToServiceRecord

0

我真的想通了......它試圖連接到只有第一個配對的連接。我把try catch放在for循環中,現在連接好:)