how to turn speaker on/off programmatically in android 4.0

Mayuri Khinvasara picture Mayuri Khinvasara · Aug 20, 2012 · Viewed 43.2k times · Source

I play a file through media player and I want to give options like speaker on/off, play though headset, bluetooth ,etc. I tried the below code which works well for android 2.2 but I want something that can also work for 2.2 and 4.0 both. Can you help me to programmatically turn the speaker on/off and playing via headphones?

AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    if(isOn){
        audioManager.setMode(AudioManager.MODE_IN_CALL);    
        audioManager.setMode(AudioManager.MODE_NORMAL); 
    }else{
        //Seems that this back and forth somehow resets the audio channel
        audioManager.setMode(AudioManager.MODE_NORMAL);     
        audioManager.setMode(AudioManager.MODE_IN_CALL);        
    }
    audioManager.setSpeakerphoneOn(isOn);

P.S: I have given this permission in manifest:

android.permission.MODIFY_AUDIO_SETTINGS 

Answer

Michael picture Michael · Aug 20, 2012

Something like this might work on some devices (I've only tested in on an XPeria P):

final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
// To get back to the default behaviour, use the combination FOR_MEDIA,FORCE_NONE.

The combination FOR_MEDIA, FORCE_SPEAKER is typically only used internally to route the FM-radio audio to the loudspeaker (since the FM-radio requires you to have a wired headset / headphone plugged in to act as an antenna). Devices that don't have FM-radio functionality (or uses an alternative implementation) might ignore this combination of parameters, so this method would not work on such a device.