Activity生命周期探索
1.通过代码细致的分析生命周期方法如何执行,下面是新建一个简单项目,在常用的生命周期方法上加上需要打印的Log.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.e(TAG,"onCreate");
}
@Override
protected void onStart() {
super.onStart();
Log.e(TAG,"onStart");
}
@Override
protected void onResume() {
super.onResume();
Log.e(TAG,"onResume");
}
@Override
protected void onPause() {
super.onPause();
Log.e(TAG,"onPause");
}
@Override
protected void onStop() {
super.onStop();
Log.e(TAG,"onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.e(TAG,"onDestroy");
}
@Override
protected void onRestart() {
super.onRestart();
Log.e(TAG,"onRestart");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.e(TAG,"onRestoreInstanceState");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.e(TAG,"onSaveInstanceState");
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.e(TAG, "ORIENTATION_PORTRAIT");
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.e(TAG, "ORIENTATION_LANDSCAPE");
}
}
}
1.正常启动
onCreate->onStart->onResume
2.点击Home键
onPause->onStop->onSaveInstanceState
3.切换回前台
onRestart->onStart->onResume
4.横竖屏切换
onPause->onStop->onSaveInstanceState->onDestory->
onCreate->onStart->onRestoreInstanceState->onResume //先OnDestroy在重新执行一遍生命周期
5.配置 android:configChanges=“orientation” 或者 配置android:configChanges=“screenSize”
onPause->onStop->onSaveInstanceState->onDestory->
onCreate->onStart->onRestoreInstanceState->onResume //和正常横竖切换效果一样
6.配置 android:configChanges=“orientation|screenSize” (同时配置)
(竖屏切横屏)ORIENTATION_LANDSCAPE (横屏切竖屏)ORIENTATION_PORTRAIT
7.点击Button,弹出一个Dialog,查看生命周期变化
<Button //MainActivity布局文件放一个Button
android:id="@+id/btn_click_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="onButtonClick"
android:text="Click me!"
tools:ignore="OnClick" />
public void onButtonClick(View view) { //Button点击事件
//显示一个Dialog
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("it is a dialog")
.setMessage("this is a test")
.create();
dialog.show();
}
Dialog显示和消失,Activity生命周期无任何变化
8.弹出DialogActivity,观察生命周期变化。
- 结论
DialogActivity弹出 执行onPause DialogActivity消失,执行onResume