Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if bluetooth headset connected

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.

like image 790
Jitu Avatar asked Aug 10 '17 11:08

Jitu


2 Answers

Here is my code:

/** */
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 -> {}
        }
    }
}

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.

like image 101
Alex Shevelev Avatar answered Sep 28 '22 05:09

Alex Shevelev


For a simple check, use the following. Remember to add BLUETOOTH permission to your manifest (Non Dangerous permission)

val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
return (bluetoothAdapter != null && BluetoothProfile.STATE_CONNECTED == bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET))
like image 42
Codelicious Avatar answered Sep 28 '22 07:09

Codelicious