一:Activity的生命周期方法

Android提供了很多Activity的生命周期方法,比如我们常用的onCreate、onPause、onResume等。这里主要介绍粗粒度的周期方法,诸如onPostCreate、onPostResume等
这些细粒度的周期方法可以参考Android的API文档,在你需要更细层次的控制的时候可以使用这些细粒度的方法。粗粒度的周期方法有以下几个:
onCreate()、onStart()、onResume()、onPause()、onStop()、onDestroy(),从名字上就可以看出来这些方法在什么时候执行。

二:测试Activity的生命周期方法的执行顺序

为了能更明白上这几个周期放的执行顺序,我们新建一个HelloWorld项目,在Activity中覆盖这几个方法,打印出日志就可以看出来执行顺序了

  1. 新建HelloWorld项目,详细步骤可以参见:

    Android教程之三:第一个Android应用,HelloWorld

  2. 修改main.xml内容为:
    Xml代码 复制代码
    1. <?xmlversion="1.0"encoding="utf-8"?>
    2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    3. android:orientation="vertical"
    4. android:layout_width="fill_parent"
    5. android:layout_height="fill_parent"
    6. >
    7. <TextView
    8. android:layout_width="fill_parent"
    9. android:layout_height="wrap_content"
    10. android:text="第一个Activity"
    11. />
    12. <Button
    13. android:id="@+id/second"
    14. android:layout_width="wrap_content"
    15. android:layout_height="wrap_content"
    16. android:text="打开第二个Activity"/>
    17. </LinearLayout>
    <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="第一个Activity"    /><Button android:id="@+id/second"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="打开第二个Activity"/></LinearLayout>

    这里主要是为增加一个文本显示和一个按钮用于显示信息和操作。
  3. 新建布局文件second.xml,内容如下: Xml代码 复制代码
    1. <?xmlversion="1.0"encoding="utf-8"?>
    2. <LinearLayout
    3. xmlns:android="http://schemas.android.com/apk/res/android"
    4. android:orientation="vertical"
    5. android:layout_width="fill_parent"
    6. android:layout_height="fill_parent">
    7. <TextView
    8. android:layout_width="fill_parent"
    9. android:layout_height="wrap_content"
    10. android:text="第二个Activity"
    11. />
    12. <Button
    13. android:id="@+id/exit"
    14. android:layout_width="wrap_content"
    15. android:layout_height="wrap_content"
    16. android:text="退出"/>
    17. </LinearLayout>
    <?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"  android:layout_height="fill_parent">  <TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="第二个Activity"    /><Button android:id="@+id/exit"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="退出"/></LinearLayout>
    这里主要是为增加一个文本显示和一个退出按钮用于退出当前Activity。
  4. 新建一个Activity,名字为SecondActivity,内容如下:
    Java代码 复制代码
    1. publicclassSecondActivityextendsActivity{
    2. privatefinalstaticStringTAG="SecondActivity";
    3. @Override
    4. protectedvoidonCreate(BundlesavedInstanceState){
    5. super.onCreate(savedInstanceState);
    6. Log.v(TAG,"onCreate");
    7. setContentView(R.layout.second);
    8. //退出按钮
    9. ButtonbtnExit=(Button)findViewById(R.id.exit);
    10. //为退出按钮设置单击事件
    11. btnExit.setOnClickListener(newOnClickListener(){
    12. @Override
    13. publicvoidonClick(Viewv){
    14. finish();//关闭当前Activity,也就是退出
    15. }
    16. });
    17. }
    18. @Override
    19. protectedvoidonStart(){
    20. super.onStart();
    21. Log.v(TAG,"onStart");
    22. }
    23. @Override
    24. protectedvoidonResume(){
    25. super.onResume();
    26. Log.v(TAG,"onResume");
    27. }
    28. @Override
    29. protectedvoidonPause(){
    30. super.onPause();
    31. Log.v(TAG,"onPause");
    32. }
    33. @Override
    34. protectedvoidonStop(){
    35. super.onStop();
    36. Log.v(TAG,"onStop");
    37. }
    38. @Override
    39. protectedvoidonDestroy(){
    40. super.onDestroy();
    41. Log.v(TAG,"onDestroy");
    42. }
    43. }
    public class SecondActivity extends Activity {private final static String TAG="SecondActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);Log.v(TAG, "onCreate");setContentView(R.layout.second);//退出按钮Button btnExit=(Button)findViewById(R.id.exit);//为退出按钮设置单击事件btnExit.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {finish();//关闭当前Activity,也就是退出}});}@Overrideprotected void onStart() {super.onStart();Log.v(TAG, "onStart");}@Overrideprotected void onResume() {super.onResume();Log.v(TAG, "onResume");}@Overrideprotected void onPause() {super.onPause();Log.v(TAG, "onPause");}@Overrideprotected void onStop() {super.onStop();Log.v(TAG, "onStop");}@Overrideprotected void onDestroy() {super.onDestroy();Log.v(TAG, "onDestroy");}}
    我在各个周期方法了都加了日志信息,便于跟踪Activity的运行过程
  5. 修改HelloWorld类,内容如下: Java代码 复制代码
    1. publicclassHelloWorldextendsActivity{
    2. privatefinalstaticStringTAG="HelloWorld";
    3. /**Calledwhentheactivityisfirstcreated.*/
    4. @Override
    5. publicvoidonCreate(BundlesavedInstanceState){
    6. super.onCreate(savedInstanceState);
    7. Log.v(TAG,"onCreate");
    8. setContentView(R.layout.main);
    9. //打开第二个Activity的按钮
    10. ButtonbtnSecond=(Button)findViewById(R.id.second);
    11. //设置单击事件
    12. btnSecond.setOnClickListener(newOnClickListener(){
    13. @Override
    14. publicvoidonClick(Viewv){
    15. startActivity(newIntent(HelloWorld.this,SecondActivity.class));
    16. finish();//关闭当前Activity
    17. }
    18. });
    19. }
    20. @Override
    21. protectedvoidonStart(){
    22. super.onStart();
    23. Log.v(TAG,"onStart");
    24. }
    25. @Override
    26. protectedvoidonResume(){
    27. super.onResume();
    28. Log.v(TAG,"onResume");
    29. }
    30. @Override
    31. protectedvoidonPause(){
    32. super.onPause();
    33. Log.v(TAG,"onPause");
    34. }
    35. @Override
    36. protectedvoidonStop(){
    37. super.onStop();
    38. Log.v(TAG,"onStop");
    39. }
    40. @Override
    41. protectedvoidonDestroy(){
    42. super.onDestroy();
    43. Log.v(TAG,"onDestroy");
    44. }
    45. }
    public class HelloWorld extends Activity {private final static String TAG="HelloWorld";    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        Log.v(TAG, "onCreate");        setContentView(R.layout.main);        //打开第二个Activity的按钮        Button btnSecond=(Button)findViewById(R.id.second);        //设置单击事件        btnSecond.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {startActivity(new Intent(HelloWorld.this,SecondActivity.class));finish();//关闭当前Activity}});    }@Overrideprotected void onStart() {super.onStart();Log.v(TAG, "onStart");}@Overrideprotected void onResume() {super.onResume();Log.v(TAG, "onResume");}@Overrideprotected void onPause() {super.onPause();Log.v(TAG, "onPause");}@Overrideprotected void onStop() {super.onStop();Log.v(TAG, "onStop");}@Overrideprotected void onDestroy() {super.onDestroy();Log.v(TAG, "onDestroy");}}
  6. 运行程序,分析结果,发现当程序启动的时候,日志信息为下图:

    由此可见当打开一个Activity的时候,其周期方法执行顺序为:onCreate()->onStart()->onResume(),现在点击“打开第二个Activity”按钮,看日志的输出如下图:

    当应用从Helloworld这个Activity启动SecondActivity的时候,Android会先执行HelloWorld的onPause方法,然后依次执行SecondActivity的onCreate()->onStart()->onResume()方法
    当SecondActivity呈现到屏幕上的时候再一次执行Helloworld的onStop()->onDestroy(),把HelloWorld从Activity栈中移除销毁。
    这里值得提的就是HelloWorld 中finish方法,因为执行了他所以
    HelloWorld才会从Activity栈中移除销毁,这样当你按“返回”键返回的时候就回不到HelloWorld 这个Activity的界面了,而是直接回到的Android的应用程序列表

三:分析结果

根据上面例子可见一个Activity在启动的时候会执行onCreate()->onStart()->onResume(),在结束(或离开)的时候会执行onPause()->onStop()->onDestroy(),这就是一个Activity的生命周期。
因此我们要在onCreate方法里把Activity的需要的东西准备好,也就是初始化;在onResume里对Activity里的东西做一些调整;在onPause做一些清理和保存工作(保存持久状态),因为这是最后的
机会,因为onPause完成之前Android不会结束托管Activity类的进程,而之后进程可能被结束。总结一下这几个周期方法的作用:

    1. onCreate():创建Activity调用,用于Activity的初始化,还有个Bundle类型的参数,可以访问以前存储的状态。
    2. onStart():Activity在屏幕上对用户可见时调用
    3. onResume():Activity开始和用户交互的时候调用,这时该Activity是在Activity栈的顶部。
    4. onPause():Activity被暂停时调用,也就是你要对你能看到的这个Activity说byebye的时候调用,这里可以做一些清理和保存工作
    5. onStop():Activity被停止或者Activity变成不可见时调用
    6. onDestroy():Activity被从内存中移除,一般发生在执行finish方法时或者Android回收内存的时候


好了,最后让我们看一个API提供的Activity的状态图吧,看了他相信你对Activity的生命周期会更了解,如下图:

Android系列教程之四:Activity的生命周期

四:小结

这节主要是通过一个例子分析Activity声明周期,并对常用生命周期方法做了一些说明,应该什么时候使用他们。到这里Android的很基础的东西已经说完了,

更多相关文章

  1. android 关于Location of the Android SDK has not been setup i
  2. Android中在GridView网格视图上实现item拖拽交换的方法
  3. Android中String资源文件的String.format方法(java)
  4. Android监听事件四种方法
  5. android工程建立到最后一步提示unsupported template dependency
  6. React Native嵌入到Android原生应用中、组件的生命周期、颜色、
  7. 自己封装的Android sqlite-helper.jar包使用方法
  8. Android四种点击事件方法

随机推荐

  1. C#2Android
  2. android XXXActivity和getApplicationCon
  3. Android(安卓)网络图片异步加载实例
  4. Android2.1应用开发环境的搭建
  5. android unzip java.io.UTFDataFormat Ex
  6. [置顶] android的logcat详细用法
  7. Android如何运行真机在eclipse上调试应用
  8. ADB和DDMS简介
  9. Android中的Content Provider
  10. Android(安卓)- 图片处理之Glide4.0