Android 蓝牙耳机 getConnectedDevices() 列表为空

标签 android kotlin android-bluetooth bluetooth-profile

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

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

监听器 fragment 如下:

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
        }
    }
}

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

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

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

最佳答案

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

 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}")
            }
        }
    }

关于Android 蓝牙耳机 getConnectedDevices() 列表为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60138413/

相关文章:

android - 操作栏不接受个人风格

android - 使用 Fragments 在工具栏中实现 SearchView

android - ROOM 构造函数在构建时无法匹配

java - 制作一个向arduino蓝牙模块发送信号的蓝牙服务

android - 获取蓝牙 Activity 配对设备

java - 无法安装 ANT 来克隆 Volley 库

Android Studio 默认缺少新建项目向导

android - SubscriptionManager.from() 已弃用

kotlin - 奇怪的kotlin checkNotNullParameter错误

android - 获取GATT Android中BLE特性的值