Android学习笔记之一 Activity的生命周期

来源:互联网 发布:ipad上电视直播软件 编辑:程序博客网 时间:2024/05/29 02:24

从今天开始,写博客。以后利用博客记录下自己的学习内容


公司Android开发人员走了,不得以需要学习下Android开发。刚开始看别人的代码,各种不懂,闲暇之余,恶补下Android基础知识。

Activity是什么,个人理解,是Android提供用于和用户交互的界面。

Activity的生命周期主要包括onCreate、onStart、onResume、onPause、onStop、onRestart、onDestory,关系见下图。


整个Activity生命周期流程,如上图所示,几个典型的场景如下:

当Activity开始时,将依次调用onCreate、onStart、onResume方法,执行完成后,显示Activity对应UI界面。

当Acitivity开始后,用户按Back键时,依次调用onPause,onStop,onDestory方法,生命周期结束。

当Activity开始后,用户按Home键时,或者调用了其他的application,一次调用onPause,onStop方法。

public class ExampleActivity extends Activity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // The activity is being created.    }    @Override    protected void onStart() {        super.onStart();        // The activity is about to become visible.    }    @Override    protected void onResume() {        super.onResume();        // The activity has become visible (it is now "resumed").    }    @Override    protected void onPause() {        super.onPause();        // Another activity is taking focus (this activity is about to be "paused").    }    @Override    protected void onStop() {        super.onStop();        // The activity is no longer visible (it is now "stopped")    }    @Override    protected void onDestroy() {        super.onDestroy();        // The activity is about to be destroyed.    }}

对Activity生命周期中几个方法的理解:

1、onCreate VS onStart

官方文档中描述:

~~onCreate~~

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

~~onStart~~

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

即onCreate是当Activity创建时调用,用户用来初始化UI中的Views、数据绑定等。

onStart方法实在Activity变为可见时调用。

onCreate方法只能调用一次,而onStart方法可以多次调用。

2、onStart VS onResume

onStart文档中指出,onStart执行之后,会执行onResume方法,那为何还要多次一举,给出onStart接口呢,搜到了几篇比较好的文章解释

http://stackoverflow.com/questions/4553605/difference-between-onstart-and-onresume

http://blog.csdn.net/zhao_3546/article/details/12843477





0 0
原创粉丝点击