简体   繁体   中英

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!

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

活动生命周期

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.

在您的活动启动之后以及打入电话之间会在暂停时呼叫on。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM