问题
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!
回答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.
回答2:
I think your question might have some duplicates:
- Check whether headphones are plugged in
- 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.
回答3:
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
回答4:
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!
来源:https://stackoverflow.com/questions/19338612/doing-something-if-it-detects-that-headphones-are-plugged-in