Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable all sound effects (hardware keys too) on Android

I'm testing my app on Samsung Galaxy S3, which has two touch buttons the back button and the menu button

I set soundEffectsEnabled to false to all of my root views, and tried with making a custom theme (as pointed out in here) and setting that theme on the application's manifest file (I tried adding it to each Activity element, too). No success.

Here is my xml file in res/values:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyCustomTheme" parent="@android:style/Theme.NoTitleBar.Fullscreen">
    <item name="android:soundEffectsEnabled">false</item>
</style>
</resources>

And the opening tag of my Application element:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/MyCustomTheme" >

It builds and runs properly. NoTitleBar.Fullscreen works too, but the back and menu touch buttons play the sound still.

like image 428
Thomas Calc Avatar asked Jul 25 '12 20:07

Thomas Calc


1 Answers

You can use the AudioManager to mute all system sounds while your application or any of your activities are running.

setStreamMute(int, boolean)

Mute or unmute an audio stream.

The mute command is protected against client process death: if a process with an active mute request on a stream dies, this stream will be unmuted automatically.

The mute requests for a given stream are cumulative: the AudioManager can receive several mute requests from one or more clients and the stream will be unmuted only when the same number of unmute requests are received.

For a better user experience, applications MUST unmute a muted stream in onPause() and mute is again in onResume() if appropriate.

So, the implementation looks like this

@Override
protected void onResume() {
    super.onResume();
    AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}

@Override
protected void onPause() {
    AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    audioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
    super.onPause();
}
like image 200
mpkuth Avatar answered Oct 04 '22 17:10

mpkuth