【问题标题】:How to detect that the disconnecting bluetooth audio device is the current device playing the music stream?如何检测断开的蓝牙音频设备是当前播放音乐流的设备?
【发布时间】:2015-04-13 15:44:24
【问题描述】:

我的音频播放器应用当前正在侦听ACTION_ACL_DISCONNECTED 事件,检查BluetoothDevice.EXTRA_DEVICE 的意图,并检查设备的类以查看它是否是BluetoothClass.Device.Major.AUDIO_VIDEO 设备。如果是这样,那么我想暂停播放。基本上,当蓝牙耳机或汽车连接断开时暂停。

但是,我发现这对一些实际上以其他方式收听的用户来说很有吸引力。例如,与蓝牙扬声器配对并听一会儿。然后插入有线耳机;播放不会错过任何一个节拍,蓝牙扬声器不再接收音频但仍处于连接状态。如果我失去蓝牙连接(关闭扬声器或走出范围),我的播放将暂停,但我不希望它暂停,因为 STREAM_MUSIC 音频实际上是通过有线耳机传输的。

当我收到ACTION_ACL_DISCONNECTED 时,我如何判断该设备是否是当前正在接收音乐流的设备? BluetoothDevice 课上有什么东西吗?我可以查询AudioManager 或其他一些系统服务来了解哪个设备正在接收音频流并将其与我刚刚收到断开广播的设备进行比较吗?有什么想法吗?

更新:

我看到 AudioManager 提供了 isBluetoothA2dpOn()isBluetoothScoOn()isSpeakerphoneOn()isWiredHeadsetOn()

这适用于我的示例。如果用户已从蓝牙扬声器切换到有线耳机,isBluetoothA2dpOn 返回 False,因此我可以忽略断开连接事件。但是,如果用户从一个蓝牙连接更改为另一个呢? isBluetoothA2dpOn 将返回 True,但 ACTION_ACL_DISCONNECTED 可能用于未接收音频的设备?

【问题讨论】:

  • 感谢编辑。

标签: android bluetooth


【解决方案1】:

您也可以注册广播接收器并播放/暂停音乐。这是我在汽车中使用的音乐应用的 kotlin 实现

class BluetoothConnectionStateReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
            val intentAction = intent.action ?: return
            // only interested in BT connection state regardless of other STATE_CHANGED
            BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED -> {
                when (intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, -1)) {
                    BluetoothAdapter.STATE_DISCONNECTED -> {
                        logMessage("STATE_DISCONNECTED")
                        // pause music
                    }
                    BluetoothAdapter.STATE_CONNECTED -> {
                        logMessage("STATE_CONNECTED")
                        // auto play music
                    }
                }
            }
        }
    }
}

然后在你的清单中声明你的接收者

<receiver
    android:name=".music.player.BluetoothConnectionStateReceiver"
    android:enabled="true">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED" />
    </intent-filter>
</receiver>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2013-12-08
    • 2011-05-31
    • 2016-01-09
    • 1970-01-01
    相关资源
    最近更新 更多