Gavin
Gavin

Reputation: 97

Android, something won't work in onCreate(), but it will in onResume()

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!

Upvotes: 0

Views: 121

Answers (3)

Parvesh Khan
Parvesh Khan

Reputation: 1616

on Pause will call when after your activity launched and in between a phone call comes.

Upvotes: 0

rockar06
rockar06

Reputation: 454

According to life cycle of Android Activity, you are calling to changeRingtone() method twice, you should call this method only in your onResume method.

Activity life cycle

Upvotes: 2

Omar Mohamed
Omar Mohamed

Reputation: 53

Quoting this article from the official Android training:

By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you'd like to restore, such as member variables that track the user's progress in the activity.

For further explanations, check also this StackOverFlow post.

Upvotes: 0

Related Questions