I am making an android app for testing phones and I need to be able to play a tone via the earphone speaker while headphones are plugged in. I am able to get the tone to play via the ear speaker when the headphones are not plugged in, but not when they are plugged in. Is there anyway to get my tone to play via the ear speaker when the headphones are plugged in? I will include the code that works without the headphones in.
mp = MediaPlayer.create(getApplicationContext(), R.raw.tone_1ghz_5sec);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
//set to false for through headphones
audioManager.setSpeakerphoneOn(false);
mp.start();
In other activities, I used the audio system class to force the speakers, is this the key here?
I was able to get it to work. You can get it to go through the ear speaker, or call speaker, whatever you want to call it by the above code. If you then want to get it to still play via the call speaker, even though headphones are plugged in, you can do it just like this:
AudioManager manager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
Class<?> cl = null;
try {
cl = Class.forName("android.media.AudioManager");
setDeviceConnectionState = cl.getMethod("setWiredDeviceConnectionState", new Class[] {
Integer.TYPE, Integer.TYPE, String.class });
//4 is for the headset with microphone 8 is for headset without microphone
//0 is for off and 1 is for on
setDeviceConnectionState.invoke(manager, new Object[] { 4 , 0, "device" });
setDeviceConnectionState.invoke(manager, new Object[] { 8 , 0, "device" });
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}