检测蓝牙耳机是否连接 [英] Detect if bluetooth headset connected

查看:79
本文介绍了检测蓝牙耳机是否连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VOIP 应用程序上工作,在静音模式下,警报音或铃声应仅在蓝牙耳机上播放.如果已连接,可以在耳机上播放,但如果未连接耳机,虽然手机处于静音模式,但扬声器上会播放声音.

Working on a VOIP application, in silent mode an alert tone or ringtone should play on bluetooth headset only. Able to play it on headphone if connected but if the headset is not connected the tone plays on the speaker though the mobile is in silent mode.

有没有办法检测蓝牙耳机是否已连接,请大佬解释一下.

Someone please explain if there is a way to detect that a bluetooth headset is connected.

推荐答案

这是我的代码:

/** */
class BluetoothStateMonitor(private val appContext: Context): BroadcastReceiver(), MonitorInterface {
    var isHeadsetConnected = false
    @Synchronized
    get
    @Synchronized
    private set

    /** Start monitoring */
    override fun start() {
        val bluetoothManager = appContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothManager.adapter.getProfileProxy(appContext, object:BluetoothProfile.ServiceListener {
            /** */
            override fun onServiceDisconnected(profile: Int) {
                isHeadsetConnected = false
            }

            /** */
            override fun onServiceConnected(profile: Int, proxy: BluetoothProfile?) {
                isHeadsetConnected = proxy!!.connectedDevices.size > 0
            }

        }, BluetoothProfile.HEADSET)

        appContext.registerReceiver(this, IntentFilter(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED))
    }

    /** Stop monitoring */
    override fun stop() {
        appContext.unregisterReceiver(this)
    }

    /** For broadcast receiver */
    override fun onReceive(context: Context?, intent: Intent?) {
        val connectionState = intent!!.extras!!.getInt(BluetoothAdapter.EXTRA_CONNECTION_STATE)
        when(connectionState) {
            BluetoothAdapter.STATE_CONNECTED -> isHeadsetConnected = true
            BluetoothAdapter.STATE_DISCONNECTED -> isHeadsetConnected = false
            else -> {}
        }
    }
}

让我解释一下.您应该同时使用 ProfileProxy 和 BroadcastReceiver.ProfileProxy 可让您检测在运行应用程序之前连接耳机的情况.反过来,BroadcastReceiver 可让您在执行应用时检测耳机何时连接/断开.

Let me explain one moment. You should use ProfileProxy and BroadcastReceiver both. ProfileProxy lets you detect the case when the headset was connected before the app was run. BroadcastReceiver, in turn, lets you detect when the headset is connected/disconnected while your app is being executed.

这篇关于检测蓝牙耳机是否连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆