how to turn speaker on/off programmatically in android 4.0

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.

Leave a Comment