How to check if a headset is connected or not?

I used the code below to verify that the headset is connected or not in onCreate Mehod.

But each time it gives me an output not connected.

AudioManager audio=(AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        if(audio.isWiredHeadsetOn()){
             Toast.makeText(this,"Connected",Toast.LENGTH_SHORT).show();
        }else{
             Toast.makeText(this,"Not Connected",Toast.LENGTH_SHORT).show();
        }

No one can say what is wrong with the code above.

Thank.

+5
source share
2 answers

Add this permission to your manifest file

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
+3
source

You need to register a bradcast event (ACTION_HEADSET_PLUG).

in intent.getIntExtra ("state", 0); you can get if a headset is connected.

Hope this helps.

+1
source

All Articles