if (!isHeadsetPlugged()) {
// if the state is "not connected", restore the speaker state.
PhoneUtils.restoreSpeakerMode(getApplicationContext());
} else {
// if the state is "connected", force the speaker off without
// storing the state.
PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false);
}
From:
https://android.googlesource.com/platform/packages/apps/Phone/+/5bcbca1162b1b462d15ebb4a5b2859a076d382e2/src/com/android/phone/PhoneApp.java
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
mIsHeadsetPlugged = (intent.getIntExtra("state", 0) == 1);
if (!isHeadsetPlugged()) { // if the state is "not connected", restore the speaker state. PhoneUtils.restoreSpeakerMode(getApplicationContext()); } else { // if the state is "connected", force the speaker off without // storing the state. PhoneUtils.turnOnSpeaker(getApplicationContext(), false, false); }