I am developing a simple app , that should toggle between speaker phone and wired headset to play audio on a button click event. I am trying to make use of isWiredHeadsetOn() function, but it says that this is deprecated for Android API lvl 5 onwards. So how do I check if currently audio is playing or not through wired headset so that I can redirect it to the phone speaker?
Note: I start my app with the headphone plugged to the 3.5mm jack of the phone.
This is my attempt at the code so far:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_re_direct);
redirect = (Button)findViewById(R.id.redirect);
final AudioManager audio =(AudioManager)getApplicationContext().getSystemService(AUDIO_SERVICE);
redirect.setOnClickListener(new View.OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(audio.isWiredHeadsetOn())
{
audio.setWiredHeadsetOn(false);
audio.setSpeakerphoneOn(true);
Toast.makeText(getApplicationContext(), "SpeakerPhone On", Toast.LENGTH_LONG).show();
redirect.setText("Turn on headset");
}
else
{
audio.setSpeakerphoneOn(false);
audio.setWiredHeadsetOn(true);
Toast.makeText(getApplicationContext(), "Wired Headset On", Toast.LENGTH_LONG).show();
redirect.setText("Turn off headset");
}
}
});
}
But the app is not toggling at all. Initially it detects that the wired headset is present, shows the Toast message SpeakerPhone On and that's it. It does not toggle between the two.
Someone please help me to make this work. Thanks.
you have to register a receiver for ACTION_HEADSET_PLUG intent and make a receiver class to catch that broadcast from that you can implement your own logic please check this
Finally managed to solve my own problem using this work around (as suggested by @noelicus):
How to mute audio in headset but let it play on speaker programmatically?
Posted for reference to others who might get stuck like me. :)
AudioManager mAudioMgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
mVolumeButton = (Button)findViewById(R.id.btn_Volume);
mVolumeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(mAudioMgr.isWiredHeadsetOn()){
mAudioMgr.setWiredHeadsetOn(false);
mAudioMgr.setSpeakerphoneOn(true);
mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION);
Toast.makeText(getApplicationContext(), "SpeakerPhone On", Toast.LENGTH_LONG).show();
}else{
mAudioMgr.setMode(AudioManager.MODE_IN_COMMUNICATION);
mAudioMgr.setSpeakerphoneOn(false);
mAudioMgr.setWiredHeadsetOn(true);
Toast.makeText(getApplicationContext(), "Wired Headset On", Toast.LENGTH_LONG).show();
}
}
});
来源:https://stackoverflow.com/questions/20947960/how-to-check-and-redirect-audio-between-wired-headset-and-speaker-phone