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

问题描述

在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.

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

07-16 02:55