javaandroidaudioandroid-audiomanagerheadset

Is it possible to ignore plugged in Headset and still use phone speakers?


I would like to use the Phone Speakers while a Headset is plugged-in, instead of the Headset-Speakers. enter image description here

Is it possible to do that? if yes, how can I achieve it?
I'm developing an App in Java for Android 9.
Detection if Headset is Plugged in works so far:

public class HeadsetIntentReceiver extends BroadcastReceiver {
private String TAG = "HeadSet";

public HeadsetIntentReceiver() {
    Log.d(TAG, "Created");
}

@Override
public void onReceive(Context context, Intent intent) {
    if(intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        switch(state) {
            case(0):
                Log.d(TAG, "Headset unplugged");
                break;
            case(1):
                Log.d(TAG, "Headset plugged");
                break;
            default:
                Log.d(TAG, "Error");
        }
    }
}
}

EDIT:
I tried the following Solutions, but Nothing happend:

  1. How to mute audio in headset but let it play on speaker programmatically?
  2. How to disable the wired headset programmatically in Java

    Thanks in Advance for any helpful advice.


(Please don't answer "Unplug the Headset")


Solution

  • I think you are looking for AudioManager

    Attach AUDIO_SERVICE to AudioManager, set AudioManager as MODE_IN_COMMUNICATION and then set your speaker phone on. You can use the speaker as if you were talking on the phone.

    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    audioManager.setSpeakerphoneOn(true);
    

    Remember to restore it after use. for example,

    protected void onPause() {
        super.onPause();
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setSpeakerphoneOn(false);
    }