简体   繁体   English

Android,onCreate()无法使用某些功能,但onResume()可以使用

[英]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. 我有一个Android应用程序,可将铃声音量更改为最大,并在退出或按下主屏幕按钮时恢复铃声音量。 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() . 现在的问题是,当应用程序首次启动(调用onCreate() )时,它会将卷更改为max,但没有将其还原到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() . 但是,如果应用程序由onResume()启动(意味着该应用程序处于后台),它将把音量更改为max,并确实将其还原到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. 根据Android Activity生命周期,您将两次调用changeRingtone()方法,因此仅应在onResume方法中调用此方法。

活动生命周期

Quoting this article from the official Android training: 引用来自官方Android培训的这篇文章:

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). 默认情况下,系统使用Bundle实例状态来保存有关活动布局中每个View对象的信息(例如,输入到EditText对象中的文本值)。 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. 有关更多说明,请另请参阅 StackOverFlow帖子。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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