2

在我的应用程序中,我想获取有关连接的蓝牙耳机的某些详细信息。首先,我想获取配置文件为耳机的连接设备。

 val result =  BluetoothAdapter.getDefaultAdapter()
        .getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)

监听器片段如下:

private var mBluetoothHeadset: BluetoothHeadset? = null
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.connectedDevices
            devices?.forEach {
                println(it.name)
            }
        }
    }

    override fun onServiceDisconnected(profile: Int) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = null
        }
    }
}

我已经在清单中声明了必要的权限

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

mBluetoothHeadset?.connectedDevices总是返回一个空列表。但在我的平板电脑中,该设备已经连接到蓝牙耳机。我在这里错过了什么吗?

4

1 回答 1

0

看起来我们可以通过根据各种连接状态进行过滤来获取连接设备的列表。以下片段对我有用

 private val states = intArrayOf(
    BluetoothProfile.STATE_DISCONNECTING,
    BluetoothProfile.STATE_DISCONNECTED,
    BluetoothProfile.STATE_CONNECTED,
    BluetoothProfile.STATE_CONNECTING
)
private val mProfileListener = object : BluetoothProfile.ServiceListener {
    override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
        if (profile == BluetoothProfile.HEADSET) {
            mBluetoothHeadset = proxy as BluetoothHeadset
            val devices = mBluetoothHeadset?.getDevicesMatchingConnectionStates(states)
            devices?.forEach {
                println("${it.name} ${it.bondState}")
            }
        }
    }
于 2020-02-19T16:44:23.220 回答