Creating an Activity
Implementing a user interface
Declaring the activity in the manifest
Using intent filters
Starting an Activity
Starting an activity for a result
Shutting Down an Activity
finish()
finishActivity(int requestCode) 强制关闭之前启动的activity
Managing the Activity Lifecycle
Resumed
The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)
Paused
Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive (the Activity
object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.
Stopped
The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity
object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.
Implementing the lifecycle callbacks
Saving activity state
当activity处于pause和stop的状态时,可能会被强制关闭,这时就需要保存activity的状态,以便有更好的用户体验。
onSaveInstanceState() onRestoreInstanceState()
只有在activity非正常退出(被回收或者强制关闭)时,onSaveInstanceState()才会调用。
即使你没有实现onSaveInstanceState()和onRestoreInstanceState()方法,activity的Layout上的控件(原生的)也是默认实现了这两个方法。
除非你给控件指定了android:saveEnabled属性为false,或者调用setSaveEnable方法。另外,没有指定id的控件,系统默认不保存状态。
虽然控件会自动保存状态,但是有时候我们还是需要保存一些成员变量,所以就必须实现activity的onSaveInstanceState()和onRestoreInstanceState()。
If the system callsonSaveInstanceState()
, it does so before onStop()
and possibly before onPause()
.
Handling configuration changes
Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language).
发生上面的变化时,系统会自动调用onDestory()和onCreate()方法。
The best way to handle such a restart is to save and restore the state of your activity usingonSaveInstanceState()
and onRestoreInstanceState()
(or onCreate()
), as discussed in the previous section.
Coordinating activities
在同一个进程中,activityA启动activityB,A和B的生命周期是这样的:
1.A的onPause()执行
2.B的onCreate(), onStart(), onResume()顺序执行
3.A的onStop()执行,如果此时A不可见。