Is there any way to force audio through the speakers when headphones are plugged in?
The answer turned out to be the following, with tips from Android - Getting audio to play through earpiece
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(true);
Ignore setRouting, it does nothing in APK > 10. Ignore comments about setMode. Ignore comments about setWiredHeadsetOn. Make sure you have MODIFY_AUDIO permissions.
Thanks to some comments here, and after some search I finally found out how to do this.
My code below is called when I press a button. It sets up audio for activating speakers while calling, then calls the number.
Pay attention to the comments in my code regarding permissions.
buttonRep.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1) we need to detect once the call has been established
//Note : this requires READ_PHONE_STATE permission in your manifest
final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(new PhoneStateListener()
{
@SuppressWarnings("unused")
@Override
public void onCallStateChanged (int state, String incomingNumber)
{
if(state == TelephonyManager.CALL_STATE_OFFHOOK) //Here we are
{
//2) we switch sound to speakers
//Note : this requires MODIFY_AUDIO_SETTINGS permission in your manifest
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_CALL);
am.setSpeakerphoneOn(true);
int i = state;
//3) we don't need this call listener anymore so we "destroy it"
tm.listen(this, PhoneStateListener.LISTEN_NONE);
}
}
}
, PhoneStateListener.LISTEN_CALL_STATE);
//4) we are ready to place our call now
//Note : this requires CALL_PHONE permission in your manifest
Intent action = new Intent();
action.setAction(Intent.ACTION_CALL);
action.setData(Uri.parse("tel:660")); //660 is my answering-machine number :)
MainActivity.this.startActivity(action);
}
});
Try this:
AudioManager mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
IntentFilter iFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
Intent iStatus = getApplicationContext().registerReceiver(null, iFilter);
boolean isHeadsetOn = false;
if (iStatus != null) {
isHeadsetOn = iStatus.getIntExtra("state", 0) == 1;
}
if(mAudioManager.isWiredHeadsetOn() || isHeadsetOn)
{
//When headphones are plugged
mAudioManager.setMode(AudioManager.MODE_CURRENT);
mAudioManager.setSpeakerphoneOn(true);
}else {
//When headphones are not plugged
mAudioManager.setMode(AudioManager.MODE_IN_CALL);
mAudioManager.setSpeakerphoneOn(true);
}