2015-05-04 189 views
4

無論配置文件如何,我如何獲得所有連接的藍牙設備的列表?Android藍牙獲取連接的設備

或者,我看到您可以通過BluetoothManager.getConnectedDevices獲取特定配置文件的所有連接設備。

而且我想我可以看到哪些設備通過ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED用於連接/斷開連接收聽...似乎很容易出錯

但我想知道是否有一個更簡單的方法來獲取所有連接的藍牙設備的列表。

+0

你只是聽是正確的acl connected/disconnect存在問題,因爲它可能在您的應用未運行或收聽廣播時發生 – behelit

回答

0

要查看完整列表,這是一個2步操作:當前配對設備

  • 掃描,或發現的

    1. 獲取列表,所有的人在範圍

    要獲取當前配對設備的列表並重復:

    Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices(); 
    if (pairedDevices.size() > 0) { 
        for (BluetoothDevice d: pairdDevices) { 
         String deviceName = d.getName(); 
         String macAddress = d.getAddress(); 
         Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress); 
         // do what you need/want this these list items 
        } 
    } 
    

    發現有點多一個複雜的操作。要做到這一點,你需要告訴BluetoothAdapter開始掃描/發現。當它發現事情時,它發出你需要用BroadcastReceiver接收的Intents。

    首先,我們將設置接收器:

    private void setupBluetoothReceiver() 
    { 
        BroadcastRecevier btReceiver = new BroadcastReciver() { 
         @Override 
         public void onReceive(Context context, Intent intent) { 
          handleBtEvent(context, intent); 
         } 
        }; 
        IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
        // this is not strictly necessary, but you may wish 
        // to know when the discovery cycle is done as well 
        eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
        myContext.registerReceiver(btReceiver, eventFilter); 
    } 
    
    private void handleBtEvent(Context context, Intent intent) 
    { 
        String action = intent.getAction(); 
        Log.d(LOGTAG, "action received: " + action); 
    
        if (BluetoothDevice.ACTION_FOUND.equals(action)) { 
         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
         Log.i(LOGTAG, "found device: " + device.getName()); 
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
         Log.d(LOGTAG, "discovery complete"); 
        } 
    } 
    

    現在所有剩下的就是告訴BluetoothAdapter開始掃描:

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); 
    // if already scanning ... cancel 
    if (btAdapter.isDiscovering()) { 
        btAdapter.cancelDiscovery(); 
    } 
    
    btAdapter.startDiscovery();