我们通过编写测试程序来分析其生命周期。
import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("MainActivity","onCreate()被调用"); } @Override protected void onStart() { super.onStart(); Log.d("MainActivity","onStart()被调用"); } @Override protected void onResume() { super.onResume(); Log.d("MainActivity","onResume()被调用"); } @Override protected void onPause() { super.onPause(); Log.d("MainActivity","onPause()被调用"); } @Override protected void onStop() { super.onStop(); Log.d("MainActivity","onStop()被调用"); } @Override protected void onDestroy() { super.onDestroy(); Log.d("MainActivity","onDestroy()被调用"); } @Override protected void onRestart() { super.onRestart(); Log.d("MainActivity","onRestart()被调用"); } }
当我们一开始启动app时,会调用依次调用OnCreate()->OnStart()->OnResume()
当我们将app移动到后台时,会依次调用OnPause()->OnStop()
当我们再次将app从后台点击到前台屏幕上是,会依次调用OnRestart()->OnStart()->OnResume()
当我们将app退出时,会依次调用OnPause()->OnStop()->OnDestroy()