Android Activity生命周期
- 新建一个“HelloWorld"工程,如果不知道怎么创建,请参考上一篇:Hello, Android Studio!
- 打开MainActiviy.java文件,重载onPause, onStart, onResume, onDestory, onRestart和onStop这六个方法,完整代码如下:
package com.test.helloworld; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; public class MainActivity extends Activity { final String TAG = "Hello world"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(TAG, "onCreate..."); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause..."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume..."); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy..."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart..."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart..."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop..."); } }
- 运行程序,log结果如下:
- 点击返回键,log结果如下:
总结如下:activity启动的时候,依次调用onCreate->onStart->onResume; 如果用户按下退出键,就依次调用onPause->onStop->onDestory。详细请看
android develop网上的activity生命周期图: