In the application, I am developing we have to notify the user via beep sound when an update to foreground Service happens.
We use this foreground service for audio recording. To play beep we use the speaker. We enable phones speakers before playing beep and disable on beep completely played, as follows :
stopSoundPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
SpeakerManager.get().disable();
.....
}
});
SpeakerManager.get().enable();
stopSoundPlayer.start();
I have following permissions in Manifest :
// Audio related permissions
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
// Other permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The runtime audio recording permission is managed properly.
But when my application is installed on any phone it automatically decreases the volume of all other applications which are audio playing. When I uninstall my application audio volume is restored. What may have caused this?
For reference below is my SpeakerManager class :
public class SpeakerManager {
private static SpeakerManager instance;
private final AudioManager audioManager;
private SpeakerManager(Context context) {
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.STREAM_MUSIC);
}
public static void init(Context context) {
instance = new SpeakerManager(context);
}
public static SpeakerManager get() {
if (instance == null) {
throw new IllegalStateException("SpeakerManager should be initialized by calling init()");
}
return instance;
}
public void enable() {
if (null != audioManager) {
audioManager.setSpeakerphoneOn(true);
}
}
public void disable() {
if (null != audioManager) {
audioManager.setSpeakerphoneOn(false);
}
}
}
I have followed Akhils answer, but with minor changes :
Change 1: Removed below line from constructor as I want use this in service.
activity.setVolumeControlStream(AudioManager.STREAM_MUSIC);
Change 2: As I wanted to play this beep as notification sound I changed following line mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tomediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
Hence bounty goes to Akhil :)