安卓学习经验 — Activity生命周期
Activity完整的生命周期:从第一次调用onCreate()开始直到调用onDestroy()结束
1、Activity栈的概念 : 先进后出规则,当一个activity 启动另外一个的时候,新的activity 就被压入栈,并成为当前运行的activity。而前一个activity 仍保持在栈之中。当用户按下BACK 键的时候,当前activity 出栈,而前一个恢复为当前运行的activity,栈中保存的其实是对象,栈中的Activity不会重排,只会新加入或移出。
2、Activity生命周期:
3、生命周期中的方法:
void onCreate(Bundle savedInstanceState) void onStart() void onRestart() void onResume() void onPause() void onStop() void onDestroy()
onCreate() :Activity设置布局文件,按钮绑定监听器等静态操作
onStart() :Activity可见但未获得用户焦点时
onRestart() : Activity已经停止然后重新被启动时
onResume() : Activity暂停后重新进入,对用户可见且可获得用户焦点时
onPause() :启动另外一个新的Activity时、按下HOME键、按下电源按键关闭屏幕时、横竖屏切换时;
假如activity被系统回收,则应重写onSaveInstanceState()保存当前activity状态,然后下次回到该activity时在onCreate(Bundle savedInstanceState)恢复
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (null != savedInstanceState) { String teststr = savedInstanceState.getString("teststr");
//dowhat } } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString("teststr", test()); }
onStop() :Activity被新的Activity完全覆盖时
onDestroy() :当Activity被系统销毁杀掉时系统调用,(整个生命周期只调用1次)用来释放onCreate ()方法中创建的资源
举例说明:ActivityOne(主Activity)、ActivityTwo、ActivityThree 互相跳转
启动ActivityOne时:
onCreate (ActivityOne) - onStart (ActivityOne) - onResume(ActivityOne)
ActivityOne跳转到ActivityTwo时:
onPause(ActivityOne) - onCreate(ActivityTwo) - onStart(ActivityTwo) - onResume(ActivityTwo)
ActivityTwo回跳到ActivityOne时:
onPause(ActivityTwo) - onActivityResult(ActivityOne) - onResume(ActivityOne) - onStop(ActivityTwo) - onDestroy(ActivityTwo)
ActivityOne在跳转到ActivityThree时:
onPause(ActivityOne) - onCreate(ActivityThree) - onStart(ActivityThree) - onResume(ActivityThree) - onStop(ActivityOne)
ActivityThree回跳到ActivityOne时:
onPause(ActivityThree) - onActivityResult(ActivityOne) - onRestart(ActivityOne) - onStart(ActivityOne)- onResume(ActivityOne) - onStop(ActivityThree) - onDestroy(ActivityThree)
ActivityOne退出时:
onPause(ActivityOne) - onStop(ActivityOne) - onDestroy(ActivityOne)