// Check if a speaker is connected
if (bluetoothAdapter.getProfileConnectionState(BluetoothHeadset.HEADSET) == BluetoothHeadset.STATE_CONNECTED)
sendSpeechToSpeaker()
sendSpeechToPhone()
问题1,
,对上面的问题是否有一个简单的修正,只会检测连接的耳机?
我的解决办法是单独检查每个连接的蓝牙设备,忽略那些不是耳机的设备。
问题2,
,有人能提出比我的解决办法更简单的方法吗?
解决办法
在初始化过程中,每个连接的蓝牙设备都会被检查,如果它们实际上是一个耳机,音频将被重新路由。
检查每个连接设备的btServiceListener
val btServiceListener: ServiceListener = object : ServiceListener {
// used to scan all CONNECTED Bluetooth devices looking for external speakers ...
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET) {
val connectionStates = intArrayOf(BluetoothProfile.STATE_CONNECTED)
// get all connected headsets
val connectedHeadsetList = proxy.getDevicesMatchingConnectionStates(connectionStates)
for (connectedHeadset in connectedHeadsetList) {
// check each headset and check if it is ACTUALLY a headset
val majorMask = BluetoothClass.Device.Major.UNCATEGORIZED // actually want to use BITMASK but some Fwit declared it private !
val isHeadset = (connectedHeadset.bluetoothClass?.deviceClass?.and(majorMask) == BluetoothClass.Device.Major.AUDIO_VIDEO)
if (isHeadset)
sendSpeechToSpeaker()
bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, proxy) // here we are finished with the proxy so clear
override fun onServiceDisconnected(profile: Int) {}
}
上面的侦听器在onCreate()中被调用
// search the list of connected bluetooth headsets
bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothAdapter = bluetoothManager.adapter
bluetoothAdapter.getProfileProxy(this, btServiceListener, BluetoothProfile.HEADSET);
听者使用大面罩耳机代码是(0x0400)三星Galaxy是可穿戴的(0x0700) TicWatch Pro 3全球定位系统是未分类的(0x1F00)