Detect programatically if headphone or bluetooth headsets attached with Android phone

In some case you might want to detect if phone’s headphone jack is in use or bluetooth headset is attached with Phone. Sharing code here to help others. Use files linked at the end of the post and use this code for detection :

/** broadcast receiver listen the headset phone/ bluetooth headset plugged in change state event **/

AudioInOutChangeReceiver.java

public class AudioInOutChangeReceiver extends BroadcastReceiver
{
    private static final String ACTION_HEADSET_PLUG_STATE = "android.intent.action.HEADSET_PLUG";

    private BluetoothHeadset mBluetoothHeadset;


    private AudioInOutChangeReceiver(Context aContext)
    {
        Log.d(getTAG(), "AudioInOutChangeReceiver()");
    
        initiBTHeadSetConfiguration();
    }

    @Override
    public void onReceive(Context context, Intent intent) 
    {   
        // initial audio manager 
        initiAudioManager(context);
        
        final String action = intent.getAction();
        // check action should not empty
        if(TextUtils.isEmpty(action))return;
         
         //Broadcast Action: Wired Headset plugged in or unplugged.
         if (action.equals(ACTION_HEADSET_PLUG_STATE)) 
         {
             updateHeadSetDeviceInfo(context, intent);
             
    } 
    //Broadcast Action: BluetoothA2dpOff Headset plugged in or unplugged.
    else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)
                || BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)
                || BluetoothAdapter.ACTION_STATE_CHANGED.equals(action))
         {
            
            updateBTHeadSetDeviceInfo(context, intent);
         }
    }

    public void updateHeadSetDeviceInfo(Context context, Intent intent)
    {
         //0 for unplugged, 1 for plugged.
         int state = intent.getIntExtra("state", -1);
         
         StringBuilder stateName = null;
         
         //Headset type, human readable string
         String name = intent.getStringExtra("name");
         
         // - 1 if headset has a microphone, 0 otherwise, 1 mean h2w
         int microPhone = intent.getIntExtra("microphone", -1);
         
         switch (state) 
         {
           case 0:
               stateName = new StringBuilder("Headset is unplugged");
               Log.d(getTAG(),stateName.toString());
               break;
           case 1:
               stateName = new StringBuilder("Headset is plugged");
               Log.d(getTAG(),stateName.toString());
               break;
           default:
               Log.d(getTAG(), "I have no idea what the headset state is");
         }
    }

    public void updateBTHeadSetDeviceInfo(Context context, Intent intent)
    {
        if(intent != null)
        {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if(device != null)
            {
                verifyHeadSetState(true,device);
            }
        }
    }

    private void verifyHeadSetState(boolean flag,BluetoothDevice device)
    {
        
        //TODO Wait for other wise result getting wrong 
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        int state = 0;
        HeadSetModel btheasetdmodel = null;
        if(flag)
        {
            // STATE_DISCONNECTED   0
            // STATE_CONNECTED      2
            
            // STATE_CONNECTING     1
            // STATE_DISCONNECTING  3
            
            state = mBluetoothHeadset.getConnectionState(device);
            Log.d(getTAG(), "State :" + state);
        }
        else
        {
            AudioManager am = getAudioManager();
            state = (am.isBluetoothA2dpOn() == true) ? 1 : 0;
        }
        
        switch (state) 
        {
            case 0:
            {
                Log.d(getTAG(), "isBluetoothA2dpOff()");
                btheasetdmodel= new HeadSetModel().setState(0).setStateName("BluetoothA2dpOff");
                break;  
            }
            case 1:
            {
                Log.d(getTAG(), "isBluetoothA2dpOn()");
                btheasetdmodel= new HeadSetModel().setState(1).setStateName("BluetoothA2dpOn");
                break;
            }
            case 2:
            {
                Log.d(getTAG(), "isBluetoothA2dpOn()");
                btheasetdmodel= new HeadSetModel().setState(1).setStateName("BluetoothA2dpOn");
                break;
            }
            default:
                break;
        }
    }

    private void initiBTHeadSetConfiguration()
    {
        if (mBTHeadSetManager == null)
            mBTHeadSetManager = new BluetoothHeadsetManager(mContext);
        
        mBTHeadSetManager.addListener(mHeadsetCallback);
        
        // if BT is turn on then we move next step
        if(mBTHeadSetManager.hasEnableBluetooth())
        {
            mBTHeadSetManager.connectionToProxy();
        }
    }
    
    private void resetBTHeadSetConfiguration()
    {
        mBTHeadSetManager.disconnectProxy();
    }

    public onBluetoothHeadSetListener mHeadsetCallback = new onBluetoothHeadSetListener() {        
        @Override
        public void disconnectedToProxy() 
        {
            verifyHeadSetState(false,null);
        }
        
        @Override
        public void connectedToProxy(BluetoothHeadset aBluetoothHeadset) 
        {
            mBluetoothHeadset = aBluetoothHeadset;
            if(mBluetoothHeadset != null)
            {
                verifyHeadSetState(false,null); 
            }
        }
    };
}

Register the broadcast receiver inside your activity :

@Override
protected void onResume() 
{
    super.onResume();
    // register for normal head set plugged in/out
    registerReceiver(AudioInOutChangeReceiver.getInstance(AbsBaseActivity.this).addAudioController(mAudioHeadsetController), new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    registerReceiver(AudioInOutChangeReceiver.getInstance(AbsBaseActivity.this).addAudioController(mAudioHeadsetController), new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    registerReceiver(AudioInOutChangeReceiver.getInstance(AbsBaseActivity.this).addAudioController(mAudioHeadsetController), new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
    registerReceiver(AudioInOutChangeReceiver.getInstance(AbsBaseActivity.this).addAudioController(mAudioHeadsetController), new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
}

@Override
protected void onPause() 
{
    super.onPause();
    unregisterReceiver(AudioInOutChangeReceiver.getInstance(AbsBaseActivity.this).removeAudioController());
}

You will need these 2 files (find them in zip) for this code to work, import them in your project, change package name to match your project’s and use above code.

DetectHeadphoneBTHs.zip

1) AudioInOutChangeReceiver.java

2) BluetoothHeadsetManager.java

Thanks,
Vipul

facebooktwittergoogle_plusredditpinterestlinkedinmailfacebooktwittergoogle_plusredditpinterestlinkedinmailby feather