Fernando
Fernando

Reputation: 450

Doing something if it detects that headphones are plugged in

I'm wanting to make it so if headphones are plugged in the device something happens such as a notification icon appears. (I already have the notification icon stuff done) But I can't seem to find a way to make it happen. I'm wanting something like this

if headphones_plugged_in {
do this 
}

I found this online

AudioManager.isWiredHeadsetOn()

I just don't know how I would use that. I already added the right permissions in the manifest too! If you could guide me or link me to something it would be great. Thank You!

Upvotes: 1

Views: 2611

Answers (4)

Fernando
Fernando

Reputation: 450

I found the solution.

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

Thanks guys!

Upvotes: 0

Daniel Kotin
Daniel Kotin

Reputation: 326

I think your question might have some duplicates:

  1. Check whether headphones are plugged in
  2. Android: Checking if headphones are plugged in

The method you want seems to have be deprecated in API level 14. The documentation says to use it only to check whether the headset it connected or not. So for your purposes, that will fit. However, to check whether audio is being played though it, you might need a different solution.

From your comment, it looks like you want to know how to actually use it. The function returns true or false to put it in an if statement as the argument and you'll be set.

Upvotes: 1

XorOrNor
XorOrNor

Reputation: 8978

I would set the BroadcastReceiver to get the android.intent.action.HEADSET_PLUG intent http://developer.android.com/reference/android/content/Intent.html#ACTION_HEADSET_PLUG

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006539

Add a <receiver> in your manifest that listens for the ACTION_HEADSET_PLUG broadcast. The documentation shows Intent extras that you can use to find out if the headset is plugged in (state), etc.

Upvotes: 1

Related Questions