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