关于activity的生命周期,大家都知道, onCreate()(创建)—>onStart()(显示)->onResume()(显示且获取焦点)—>onPause()(失去焦点)—>onStart()(不显示,但在任务栈)—>onDestory()(销毁)
现在假设有个Activity A跳转到Activity B,然后再按返回键返回A, 再按返回键退出程序,那么这些生命周期的调用顺序是什么呢? 如果能准确的说出Activity的生命周期的调用,那么就深刻理解了Activity的生命周期
Activity A:
public class AActivity extends Activity {
private static final String TAG = "tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"invoke AActivity onCreate");
init();
}
private void init(){
findViewById(R.id.bt_start).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(AActivity.this, BActivity.class);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG,"invoke AActivity onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.i(TAG,"invoke AActivity onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.i(TAG,"invoke AActivity onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG,"invoke AActivity onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG,"invoke AActivity onDestroy");
}
}
Activity B:
public class BActivity extends Activity {
private static final String TAG = "tag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
Log.e(TAG,"invoke BActivity onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.e(TAG,"invoke BActivity onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG,"invoke BActivity onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.e(TAG,"invoke BActivity onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.e(TAG,"invoke BActivity onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG,"invoke BActivity onDestroy");
}
}
按照刚才说的页面跳转顺序, log 如下
我们通过日志可以知道:
1,当Activity A打开时: A调用 onCreate()–>onStart()–>onResume()
创建,显示,获取焦点
2,然后再打开B时: 首先 A调用 onPause()失去焦点
B调用 onCreate()–>onStart()–>onResume() 创建,显示,获取焦点
A再调用 onStop()不在显示,压入任务栈
3,当第一次按返回键时: B首先调用 onPause()方法失去焦点
然后A调用onStart()–>onResume()显示和获取焦点
再然后B调用 onStop()–>onDestory() 不显示和销毁
4,再次按返回键
A调用 onPause()–>onStop()—>onDestory()失去焦点,不显示和销毁