How to programmatically tell if a Bluetooth device is connected?

前端 未结 7 1602
耶瑟儿~
耶瑟儿~ 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:38

    This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):

    private val mProfileListener = object : BluetoothProfile.ServiceListener {
        override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
            if (profile == BluetoothProfile.HEADSET) 
                mBluetoothHeadset = proxy as BluetoothHeadset            
        }
    
        override fun onServiceDisconnected(profile: Int) {
            if (profile == BluetoothProfile.HEADSET) {
                mBluetoothHeadset = null
            }
        }
    }
    

    Then while checking bluetooth:

    mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
    if (!mBluetoothAdapter.isEnabled) {
        return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    }
    

    It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:

    mBluetoothHeadset!!.connectedDevices
    

提交回复
热议问题