1

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!

Fernando
  • 450
  • 1
  • 7
  • 22

4 Answers4

1

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.

Community
  • 1
  • 1
Daniel Kotin
  • 326
  • 2
  • 8
  • Yes, I am aware of that. I only need it to check if they are plugged in though, no need to check if music is playing. – Fernando Oct 12 '13 at 20:11
  • Then you should be fine with something like what is shown in this post (http://stackoverflow.com/questions/6249884/audiomanager-iswiredheadseton-is-not-working-in-android) I haven't done any android dev, but I don't see why (AudioManager)getSystemService(AUDIO_SERVICE).isWiredHeadsetOn() shouldn't work. I'll leave that for someone more experienced – Daniel Kotin Oct 12 '13 at 20:16
1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

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

XorOrNor
  • 8,868
  • 12
  • 48
  • 81
0

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!

Fernando
  • 450
  • 1
  • 7
  • 22