Search code examples
androidandroid-bluetooth

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.


Solution

  • Thanks for the answer @cristallo

    This is the way I handled it.

    Connect to proxy

    bluetoothAdapter.getProfileProxy(mContext, mProfileListener, BluetoothProfile.HEADSET);
    

    Created a listener

    private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener()
    {
    
        @Override
        public void onServiceConnected(int profile, BluetoothProfile proxy)
        {
            if (profile == BluetoothProfile.HEADSET)
            {
                mBluetoothHeadset = (BluetoothHeadset) proxy;
                if(mBluetoothHeadset.getConnectedDevices().size()>0) {
                    IS_BLUETOOTH_CONNECTED = true;
                    Logs.d(TAG,"Bluetooth device is connected");
                }
                
            }
        }
    
        @Override
        public void onServiceDisconnected(int profile)
        {
             if (profile == BluetoothProfile.HEADSET)
             {
                 mBluetoothHeadset = null;
                 IS_BLUETOOTH_CONNECTED = false;
                 Logs.d(TAG,"Bluetooth device is disconnected");
             }
        }
    };
    

    Referred from Detect programatically if headphone or bluetooth headset attached with android phone

    The blogger Vipul had created a BluetoothHeadsetManager class, which handles getting the headset profile, handling the listener, checking if the bluetooth is enabled or not.I haven't utilized the Broadcast Receiver.

    switch (audioMgr.getRingerMode()) {
            case AudioManager.RINGER_MODE_SILENT:
                if(BluetoothHeadsetManager.IS_BLUETOOTH_CONNECTED) {
                    //play notification
                }
                break;
            case AudioManager.RINGER_MODE_VIBRATE:
                if(BluetoothHeadsetManager.IS_BLUETOOTH_CONNECTED) {
                    //play notification
                }
                break;
            case AudioManager.RINGER_MODE_NORMAL:
                //play ringtone
                break;
            default:
                break;
            }}