首先我们先来看一下官方的Android的生命周期图:
根据这个流程图我们可以看到Activity的生命周期一共有7个方法,那么接下来我们就来聊聊这些方法执行过程。
首先在两个Activity(MainActivity和SecondActivity)的生命周期方法中打印log以便观察
package com.example.barbrothers.blogproject; import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e("==Activity生命周期测试A==","onCreate");
} @Override
protected void onStart() {
super.onStart();
Log.e("==Activity生命周期测试A==","onStart");
} @Override
protected void onResume() {
super.onResume();
Log.e("==Activity生命周期测试A==","onResume");
} @Override
protected void onPause() {
super.onPause();
Log.e("==Activity生命周期测试A==","onPause");
} @Override
protected void onStop() {
super.onStop();
Log.e("==Activity生命周期测试A==","onStop");
} @Override
protected void onRestart() {
super.onRestart();
Log.e("==Activity生命周期测试A==","onRestart");
} @Override
protected void onDestroy() {
super.onDestroy();
Log.e("==Activity生命周期测试A==","onDestroy");
}
public void onClick(View v){
startActivity(new Intent(this,SecondActivity.class));
}
}
package com.example.barbrothers.blogproject; import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log; public class SecondActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.e("==Activity生命周期测试B==","onCreate");
} @Override
protected void onStart() {
super.onStart();
Log.e("==Activity生命周期测试B==","onStart");
} @Override
protected void onResume() {
super.onResume();
Log.e("==Activity生命周期测试B==","onResume");
} @Override
protected void onPause() {
super.onPause();
Log.e("==Activity生命周期测试B==","onPause");
} @Override
protected void onStop() {
super.onStop();
Log.e("==Activity生命周期测试B==","onStop");
} @Override
protected void onRestart() {
super.onRestart();
Log.e("==Activity生命周期测试B==","onRestart");
} @Override
protected void onDestroy() {
super.onDestroy();
Log.e("==Activity生命周期测试B==","onDestroy");
} }
1.启动Activity A:系统会先调用onCreate方法,然后调用onStart方法,最后调用onResume,Activity A进入运行状态。
2.当前Activity A被其他Activity B覆盖其上或被锁屏:系统会调用onPause方法,暂停当前Activity A的执行,然后Activity B会调用onCreate(),onStart(),onResume()方法,然后如果Activity B覆盖了这个Activity A则ActivityA会调用onStop()方法。
3.当前Activity A由被覆盖状态回到前台或解锁屏:系统会调用onRestart(),onStart(),onResume()方法,再次进入运行状态。
4.当前Activity处于被覆盖状态或者后台不可见状态,即第2步,系统内存不足,杀死当前Activity,而后用户退回当前Activity:再次调用onCreate方法、onStart方法、onResume方法,进入运行状态。
5.用户退出当前Activity:系统先调用onPause方法,然后调用onStop方法,最后调用onDestory方法,结束当前Activity。