0

I'm developing an Android application for the Droid Incredible. When I plug in my headphones, an icon appears on the status bar, so I presume the phone must know headphones are present.

My code produces beeps in response to various user inputs, but I discovered today that's a REALLY BAD idea when the user is wearing headphones. Ow.

Does anybody have suggestions for how I can detect the presence of headphones programmatically, in Android??

Thanks, R.

Rich
  • 4,157
  • 5
  • 33
  • 45

2 Answers2

3

I found the AudioManager class on the developer site, it looks to have a helpful method for this, but I have not tested it:

AudioManager am = getSystemService(Context.AUDIO_SERVICE);
bool headsetEnabled = am.isWiredHeadsetOn();
Kevin Coppock
  • 133,643
  • 45
  • 263
  • 274
  • This looks like a cool, simple addition to the code. Thanks, I'll test it tomorrow when my brane has grown back! I suppose I still need to make a Broadcast Receiver (Eek!) if I want to catch headphone connection activity in real time, but this seems like a perfect "80% solution". – Rich Nov 15 '10 at 22:49
  • Yeah, if you need it as a real time setting, this probably isn't the best for you. Prior to building out a Broadcast Receiver (I've not even messed with one of those yet) you could just have AudioManager declared as a class variable, and just preface your beep code with `if(!am.isWiredHeadsetOn()) { /* beep */ }`. – Kevin Coppock Nov 15 '10 at 23:32
  • Strangely, K, (and I'm not blaming you) isWiredHeadsetOn() doesn't appear to work at all. Neither did my code to set volume level at start up. It may be that I'm mixing apples and oranges (or AudioManagers and MediaPlayers, to be precise), however. – Rich Nov 16 '10 at 14:05
  • 1
    Haha feel free to blame me, I didn't test it. :P Looked like it should do the trick though; wonder what it is doing, then? – Kevin Coppock Nov 16 '10 at 14:36
2

You find out when it changes with http://developer.android.com/reference/android/content/Intent.html#ACTION_HEADSET_PLUG

I'm not sure if it's possible to find out if your app is started after the headphones are plugged in/plugged out.

Logan Capaldo
  • 39,555
  • 5
  • 63
  • 78