I have an Android app which changes the ringer volume to maximum and restores the volume upon exit or home button pressed. Here is the snippet of the code.
int ringMode;
int ringVolume;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeRingtone();
}
@Override
protected void onResume() {
changeRingtone();
}
private void changeRingtone() {
ringVolume = audioManager.getStreamVolume(audioManager.STREAM_RING);
ringMode = audioManager.getRingerMode();
audioManager.setStreamVolume(audioManager.STREAM_RING,
audioManager.getStreamMaxVolume(audioManager.STREAM_RING),
AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
}
@Override
protected void onPause() {
audioManager.setStreamVolume(audioManager.STREAM_RING, ringVolume, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
audioManager.setRingerMode(ringMode);
super.onPause();
}
Now the issue is, when the app first launches (onCreate()
is called), it changes the volume to max, but it doesn't restore it to previous volume in onPause()
. However, if the app is started by onResume()
(means the app was in background), it will change the volume to max and it does restore it to previous volume in onPause()
.
The code seems to be fine but I haven't figured out where is the problem for several days, please help, thanks!