懂得 Activity 的生命周期
把Activity看成一个页面,在Android系统中,Activity 被作为 Activity 栈进行管理.
- 当前活动的Activity 处于栈顶.
- 非活动的Activity 压在栈中, 处于等待状况
一个Activity的状态有如下4种:
- 活动. (处于栈顶, 有焦点,可见)
- 暂停. (失去焦点,但可见)
- 停止. (失去焦点,不可见)
- 销毁. (被系统或进程结束)
一个Activity的方法有如下7个:
- .onCreate() 创建
- .onStart() 启动
- .onRestart() 重启.
- .onResume() 恢复
- .onPause() 暂停
- .onStop() 停止
- .onDestroy() 销毁
Activity 的生命周期的 Cases
a. Activiy1 启动
- Code:
super.onCreate()
- 运行顺序: ( Activity1 : onCreate() -> onStart() ->onResume() )
b. 从Activity1 跳转到 Activity2, 然后关闭Activity1.
- Code:
Intent intent = new Intent(); //新建一个Intent对象. intent.setClass(Activity1.this, Activity2.class); //设定Intent要启动的类. startActivity(intent); //启动一个新的Activity Activity1.this.finish(); //关闭当前的Activity.
- 运行顺序: (Activity1: onPause() )-> ( Activity2: onCreate() ->onStart() ->onResume()) -> (Activity1:onStop() ->onDestroy())
c. 关闭Activity1, 退出程序 , 或者按 "BACK" 键.
- Code:
Activity1.this.finish();
-运行顺序: Activity1: onPause()->onStop()->onDestroy();
d. 按"HOME"键, 然后再运行程序.
- 运行顺序: Activity1: onPause()->onStop() => 运行其他程序 => 再运行本程序: Activity1: onRestart()->onStart()-)>onResume()
e. 刷新Activity1
- Code:
public class LifeCycleActivity extends Activity { /** Called when the activity is first created. */ private static final String TAG = "MainActivity"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Log.i(TAG, "onCreate()"); Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Intent intent = new Intent(LifeCycleActivity.this, Activity2.class); //startActivity(intent); reload(); } }); } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()"); super.onDestroy(); } @Override protected void onPause() { Log.i(TAG, "onPause()"); super.onPause(); } @Override protected void onRestart() { Log.i(TAG, "onRestart()"); super.onRestart(); } @Override protected void onResume() { Log.i(TAG, "onResume()"); super.onResume(); } @Override protected void onStart() { Log.i(TAG, "onStart()"); super.onStart(); } @Override protected void onStop() { Log.i(TAG, "onStop()"); super.onStop(); } public void reload(){ Intent intent = getIntent(); this.finish(); startActivity(intent); } }
-运行顺序: onCreate()->onStart()->onResume() ==> 点按纽后 onPause()->onCreate()->onStart()->onResume()->onStop()->onDestroy()
更多的可以参考:
http://www.ibm.com/developerworks/cn/opensource/os-cn-android-actvt/