我正在尝试了解 Android Activity 生命周期。为此,我创建了 Activity,其中覆盖了所有生命周期方法(onCreate、onStart、onRestart、onResume、onPause、onStop、onDestroy):
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d("ActivityTutorial", "onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.d("ActivityTutorial", "onStart");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d("ActivityTutorial", "onRestart");
}
@Override
protected void onResume() {
super.onResume();
Log.d("ActivityTutorial", "onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.d("ActivityTutorial", "onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.d("ActivityTutorial", "onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("ActivityTutorial", "onDestroy");
}
}
我在使用 Log.d(...) 记录日志的行上放置了断点。然后我尝试调试。 onCreate 方法没问题 - 它在创建 Activity 时调用。
奇怪的情况是启动 onStart 方法。根据 Android documentation : "onStart() 当 Activity 对用户可见时调用。"但是当我调试时,它涉及到 onStart 方法,但是这个 Activity 上的 Button 还不可见。
我认为应该在调用 onStart() 方法后看到 onResume()。但是按钮不可见。
只有在 onResume 方法之后,按钮才可见。
所以我的问题是 onStart 和 onResume 方法有什么问题?也许我正在做一些不应该做的事情?
最佳答案
没有。 onResume() 方法使 Activity 可见。正如您所说,感谢文档:“当 Activity 对用户变得可见时调用 onStart()”。
如果您仔细阅读:“onResume() 在 Activity 将开始与用户交互时调用。”
更新:
Keep in mind that onResume is not the best indicator that your activity is visible to the user; a system window such as the keyguard may be in front. Use onWindowFocusChanged(boolean) to know for certain that your activity is visible to the user (for example, to resume a game).
关于Android - onStart 方法有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32945187/