Activity是Android四大组件中,和用户直接交互的组件,直接影响到用户体验,接下来首先分析一下Activity的生命周期,
Activity有三种基本状态:
- Active:处于屏幕前景(当前task的栈顶Activity处于Active状态),同一时刻只能有一个Activity处于Active状态;
- Paused状态:处于背景画面画面状态,失去了焦点,但依然是活动状态;
- stopped:不可见,但依然保持所有的状态和内存信息。
Activity的生命周期大致可分为三组:
- The entire lifetime of an activity happens between the first call to
through to a single final call toonCreate()
.onDestroy()
-
The visible lifetime of an activity happens between a call to
until a corresponding call toonStart()
.onStop()
-
The foreground lifetime of an activity happens between a call to
until a corresponding call toonResume()
.onPause()
1,Active,处于屏幕前景(当前task的栈顶Acitivity处于active状态),同一时刻只能有一个activity处于active状态;
2,Paused状态:处于背景画面状态,失去了焦点,但依然处于活动状态,并且是可见的,
3,Stopped,不可见,但保持所有的状态和内存信息。
1,启动Activity时:首先调用onCreate()方法,接着调用 onStart()方法,然后是onResume()(接着onWindowFocusChanged()会被调用)activity获得窗口焦点,之后Activity进入正常的运行状态,
2,当前Activity被其他Activity覆盖或者锁屏时,首先调用其onPause()方法,然后是onSaveInstanceState()方法,接着调用onStop()方法,接着onWindowFocusChanged()会被调。
3, 解锁时或者重新回到Activity时, onRestart--->onStart()--->onResume()--->onWindowFocusChanged.
按Home键:onPause()--->onWindowFocusChanged()--->onSaveInstanceState()--->onStop().
锁屏时: onPause()--->onSaveInstanceState()--->onStop()--->onWindowFocusChanged()
4,如果Activity处于被覆盖或者后台不可见状态,如果系统内存紧张,Activity会被直接kill掉,重启时,走第一种情况 。当屏幕旋转时,Activity会被kill掉,并且重新创建.
5,用户退出当前Activity:系统先调用onPause方法,然后调用onStop方法,最后调用onDestory方法,结束当前Activity。
旋转屏幕:
布局文件:main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${packageName}.${activityClass}" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="click"
android:layout_below="@id/text"
/>
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btn"/>
</RelativeLayout>