How to programmatically tell if a Bluetooth device is connected?

前端 未结 7 1626
耶瑟儿~
耶瑟儿~ 2020-11-22 13:14

I understand how to get a list of paired devices but how can I tell if they are connected?

It must be possible since I see them listed in my phone\'s Bluetooth devi

7条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 13:31

    I was really looking for a way to fetch the connection status of a device, not listen to connection events. Here's what worked for me:

    BluetoothManager bm = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
    List devices = bm.getConnectedDevices(BluetoothGatt.GATT);
    int status = -1;
    
    for (BluetoothDevice device : devices) {
      status = bm.getConnectionState(device, BLuetoothGatt.GATT);
      // compare status to:
      //   BluetoothProfile.STATE_CONNECTED
      //   BluetoothProfile.STATE_CONNECTING
      //   BluetoothProfile.STATE_DISCONNECTED
      //   BluetoothProfile.STATE_DISCONNECTING
    }
    

提交回复
热议问题