最近遇到一个问题,就是Android的Activity什么时候会调用onCreate()而不调用onStart(),在正常的开发过程中很少会考虑到这个问题,只有遇到一些异常情况,才会去打断点看看生命周期的过程。
- public class MainActivity extends Activity {
- Button btn;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Log.d("TAG", "onCreate");
- // super.onStop();
- // super.onDestroy();
- finish();
- btn = (Button)findViewById(R.id.btn1);
- }
- @Override
- protected void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- Log.d("TAG", "onDestroy");
- }
- @Override
- protected void onPause() {
- // TODO Auto-generated method stub
- super.onPause();
- Log.d("TAG", "onPause");
- }
- @Override
- protected void onRestart() {
- // TODO Auto-generated method stub
- super.onRestart();
- Log.d("TAG", "onRestart");
- }
- @Override
- protected void onResume() {
- // TODO Auto-generated method stub
- super.onResume();
- Log.d("TAG", "onResume");
- }
- @Override
- protected void onStart() {
- // TODO Auto-generated method stub
- super.onStart();
- Log.d("TAG", "onStart");
- }
- @Override
- protected void onStop() {
- // TODO Auto-generated method stub
- super.onStop();
- Log.d("TAG", "onStop");
- }
- }
我们在onCreate()里面加了super.onStop();或super.onDestroy();,这样执行到onCreate()函数时,执行流程是这样的:onCreate -> onStop或onDestroy -> onStart -> onResume。最终还是会执行onStart。而如果加上finish(),则onCreate -> onDestroy,而不会执行onStart。