您的位置:首页 > 其它

Activity生命周期回调函数以及应用场景

2014-03-26 20:38 351 查看
先看一下Activity的生命周期图:



了解Activity生命周期的意义:

官网描述(http://developer.android.com/guide/components/activities.html):

When an activity is stopped because a new activity starts, it is notified of this change in state through the activity's
lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state—whether the system is creating it, stopping it, resuming it, or destroying it—andeach
callback provides you the opportunity to perform specific work that's appropriate to that state change. For
instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all
part of the activity lifecycle.

意义:每个回调函数为Activity提供了在状态改变时为应用做一些特定处理的时机。


Managing the Activity Lifecycle

Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible application. The lifecycle of an activity is directly affected by its association with other activities, its task and back stack.

An activity can exist in essentially three states:

ResumedThe activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)PausedAnother 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 iscompletely alive (the
Activity
object
isretained 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.StoppedThe activity is completely obscured(遮蔽的;湮没的) by another
activity (the activity is now in the "background"). A stopped activity is alsostill alive (the
Activity
object
isretained in memory, it maintains all state andmember 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.

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its
finish()
method),
or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.
处于Paused和Stopped状态的Activity仍然alive,保存在内存中,并且只有之前的状态和信息。所以当Activity跳转到新的Activity界面、按Home键回到主屏、按锁屏键、设备休眠,这些情况下(均为Stopped状态)再返回原来的Activity时,Activity之前的状态和信息还在。内存不足时回收内存时除外。

The two most important callback methods are:

onCreate()
You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call
setContentView()
to
define the layout for the activity's user interface.
onPause()
The system calls this method as the first indication(指示,指出;迹象;象征) that the user is leaving
your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

Note: Your
implementation of these lifecycle methods must always call the superclass implementation before doing any work, as shown in the examples above.


The entire lifetime of an activity happens between the call to
onCreate()
and
the call to
onDestroy()
.
Your activity should perform setup of "global" state (such as defining layout) in
onCreate()
,
and release all remaining resources in
onDestroy()
.
For example, if your activity has a thread running in the background to download data from the network, it might create that thread in
onCreate()
and
then stop the thread in
onDestroy()
.

The visible lifetime of an activity happens between the call to
onStart()
and
the call to
onStop()
.
During this time, the user can see the activity on-screen and interact with it. For example,
onStop()
is
called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a
BroadcastReceiver
in
onStart()
to
monitor changes that impact your UI, and unregister it in
onStop()
when
the user can no longer see what you are displaying. The system might call
onStart()
and
onStop()
multiple
times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

The foreground lifetime of an activity happens between the call to
onResume()
and
the call to
onPause()
.
During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example,
onPause()
is
called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

A summary of the activity lifecycle's callback methods.

MethodDescriptionKillable after?Next
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, and so on. This method is passed a Bundle object containing the activity's previous state, if that state was captured
(see Saving Activity State, later).
Always followed by
onStart()
.

No
onStart()
onRestart()
Called after the activity has been stopped, just prior to it being started again.
Always followed by
onStart()

No
onStart()
onStart()
Called just before the activity becomes visible to the user.
Followed by
onResume()
if the activity comes to the foreground, or
onStop()
if
it becomes hidden.
No
onResume()


or

onStop()
onResume()
Called just before the activity starts interacting with the user. At this point the activity is at the top of the activity stack, with user input going to it.
Always followed by
onPause()
.
No
onPause()
onPause()
Called when the system is about to start resuming another activity. This method is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, and so on. It should do whatever it does very quickly,
because the next activity will not be resumed until it returns.
Followed either by
onResume()
if the activity returns back to the front, or by
onStop()
if
it becomes invisible to the user.
Yes
onResume()


or

onStop()
onStop()
Called when the activity is no longer visible to the user. This may happen because it is being destroyed, or because another activity (either an existing one or a new one) has been resumed and is covering it.
Followed either by
onRestart()
if the activity is coming back to interact with the user, or by
onDestroy()
if
this activity is going away.
Yes
onRestart()


or

onDestroy()
onDestroy()
Called before the activity is destroyed. This is the final call that the activity will receive. It could be called either because the activity is finishing (someone called
finish()
on
it), or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the
isFinishing()
method.
Yesnothing

Shutting Down an Activity

You can shut down an activity by calling its
finish()
method.
You can also shut down a separate activity that you previously started by calling
finishActivity()
.

Note: In most cases, you should not explicitly finish an activity using these methods. The Android system manages the life of an activity
for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance
of the activity.

Saving activity state

处于Paused和Stopped状态的Activity仍然alive,保存在内存中,并且只有之前的状态和信息。所以当Activity跳转到新的Activity界面、按Home键回到主屏、按锁屏键、设备休眠,这些情况下(均为Stopped状态)再返回原来的Activity时,Activity之前的状态和信息还在。内存不足时回收内存时除外。

在Activity被Destory后,需要保存Activity信息时,需要调用
onSaveInstanceState()
方法。

The system calls
onSaveInstanceState()
before
making the activity vulnerable( 易受攻击的,易受…的攻击;易受伤害的;有弱点的) to destruction(破坏).
The system passes this method a
Bundle
in
which you can save state information about the activity as name-value pairs, using methods such as
putString()
and
putInt()
.
Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes the
Bundle
to
both
onCreate()
and
onRestoreInstanceState()
.
Using either of these methods, you can extract your saved state from the
Bundle
and
restore the activity state. If there is no state information to restore, then the
Bundle
passed
to you is null (which is the case when the activity is created for the first time).



Note: There'sno
guarantee that
onSaveInstanceState()
will
be called before your activity is destroyed, because there are cases in which it won't be necessary to save
the state (such as when the user leaves your activity using the Back button,
because the user is explicitly closing the activity). If the system calls
onSaveInstanceState()
,
it does so before
onStop()
and
possibly before
onPause()
.

onSaveInstanceState()方法不保证一定会在Activity销毁之前执行,onSaveInstanceState的调用遵循一个重要原则,即当系统“未经你许可”时销毁了你的activity(不是自己主动销毁activity),则onSaveInstanceState会被系统调用。

onSaveInstanceState()方法的执行顺序可能在
onStop()
方法之前,也可能在
onPause()
方法之前。


However,
even if you do nothing and do not implement
onSaveInstanceState()
,some
of the activity state is restored by the
Activity
class's
default implementation of
onSaveInstanceState()
.
Specifically, the default implementation calls the corresponding
onSaveInstanceState()
method
for every
View
in
the layout, which allows each view to provide information about itself that should be saved. Almost every widget
in the Android framework implements this method as appropriate, such that any visible changes to the
UI are automatically saved and restored when your activity is recreated
. For example, the
EditText
widget
saves any text entered by the user and the
CheckBox
widget
saves whether it's checked or not. The only work required by you is to provide a
unique ID
(with the
android:id
attribute)
for each widget you want to save its state. If a widget does not have an ID, then the system cannot save its state.

如果不需要保存额外的信息,可以不是实现onSaveInstanceState()方法,Activity会调用默认的onSaveInstanceState()方法来保存Activity的状态信息,默认的onSaveInstanceState()方法会调用Layout中每个View的相关onSaveInstanceState()方法来保存View自己的信息,几乎每个Widget都实现了onSaveInstanceState()方法来保存自己的状态信息。必须为Widget设置ID,系统此后保存该Widget的状态信息。

You
can also explicitly stop a view in your layout from saving its state by setting the
android:saveEnabled
attribute
to
"false"
or
by calling the
setSaveEnabled()
method.
Usually, you should not disable this, but you might if you want to restore the state of the activity UI differently.



Because
the default implementation of
onSaveInstanceState()
helps
save the state of the UI, if you override the method in order to save additional state information, you should alwayscall the superclass
implementation of
onSaveInstanceState()
before
doing any work. Likewise, youshould
also call the superclass implementation of
onRestoreInstanceState()
if
you override it, so the default implementation can restore view states.



Note: Because
onSaveInstanceState()
is
not guaranteed to be called, you should use it only torecord the transient(短暂的) state of the activity (the state
of the UI)—you should never use it to store persistent data.
Instead, you should use
onPause()
to
store persistent data
(such as data that should be saved to a database) when the user leaves the activity.

因为onSaveInstanceState()方法不保证会一定执行,所以应只使用该方法来保存Ativity瞬时短暂的状态信息(UI的状态),不用用该方法来保存持久化的数据,应该使用
onPause()
方法来保存持久化数据,例如存入数据库的数据。

Handling configuration changes

Some device configurations can change during runtime (such as screen orientation, keyboard availability, and language). When
such a change occurs, Android recreates the running activity (the system calls
onDestroy()
,
then immediately calls
onCreate()
).

The
best way to handle such a restart is to save and restore the state of your activity using
onSaveInstanceState()
and
onRestoreInstanceState()
(or
onCreate()
),
as discussed in the previous section.



Coordinating activities

When one activity starts another, they both experience(经历,体验) lifecycle transitions(转变). The first activity pauses and stops (though, it won't stop if it's still visible in the background), while the other activity is created. In case these activities share
data saved to disc or elsewhere, it's important to understand that the first activity is not completely stopped before the second one is created. Rather, the process of starting the second one overlaps(重叠) with the process of stopping the first one.

The order of lifecycle callbacks is well defined, particularly when the two activities are in the same process and one is starting the other. Here's the order of operations that occur when Activity A starts Acivity B:

Activity A's
onPause()
method
executes.
Activity B's
onCreate()
,
onStart()
,
and
onResume()
methods
execute in sequence. (Activity B now has user focus.)
Then, if Activity A is no longer visible on screen, its
onStop()
method
executes.

This predictable sequence of lifecycle callbacks allows you to manage the transition of information from one activity to another. For example,if you must write to a database when the first
activity stops so that the following activity can read it, then you should write to the database during
onPause()
instead
of during
onStop()
.

应用场景:

1、onCreate(): The
activity is being created.

在完整生命周期开始时调用。

执行一些在Activity生命周期只执行一次的基本的应用启动逻辑。

(1)、必须实现的方法,系统在开始创建Activity的时候调用该方法,该方法应该初始化Activity中的组件,最重要的是,要调用setContentView()方法来为Activity界面定义布局;

(2)、定义全局的状态信息(例如Layout),得到Fragment的引用;

(3)、分配对类变量的引用,初始化类变量;

(4)、将数据绑定到控件;

(5)、启动Service和定时器;

(6)、开启线程,如果需要的话;

(7)、通过
Bundle
参数保存的数据恢复被Kill掉的Activity的(onSaveInstanceState()方法中保存)状态信息。也可在onRestoreInstanceState()方法中恢复。

(8)、屏幕旋转时恢复onRestoreInstanceState()保存的Activity的信息。也可在onRestoreInstanceState()方法中恢复。

作为使用Android变形高效代码的指导原则的一部分,我们建议最好避免创建短期的对象。对象的快速创建和销毁会导致额外的垃圾收集过程,而这个过程会对用户体验产生直接的影响。如果Activity是有规律的创建相同的对象集,那么可以考虑在onCreate方法中创建他们,因为它只在Activity的生存期中被调用一次。

2、onRestart():装载改变,知道Activity在此进程中已经可见。

(1)、恢复在onStop()方法中暂停或停止的Service或者其他专门用于更新用户界面的进程。

(2)、实现那些只有当Activity在它的完整生存期之内重启时才能完成的特殊处理。

When your activity comes back to the foreground from the stopped state, it receives a call to onRestart().
The system also calls the onStart() method, which happens every time your activity becomes visible (whether being restarted or created for the first time). The onRestart() method, however, is called only when the activity resumes from the stopped state, so
you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.

you should usually use the onStart() callback method as the counterpart(配对) to the onStop() method, because the system calls onStart() both when it creates your activity and when it restarts the activity from the stopped state.

3、onStart():The
activity is about to become visible.

在可见生存周期开始的时候调用。既然Activity可见,就可以应用任何的UI改变。

(1)、维持需要展示的资源(maintain
resources that are needed to show the activity to the user),例如注册
BroadcastReceiver


(2)、改变UI。

(3)、恢复在onStop()方法中暂停或停止的Service或者其他专门用于更新用户界面的进程。

4、onResume():The
activity has become visible (it is now "resumed").

在Activity状态生存周期开始时调用。恢复当Activity处于不活动状态时被挂起的暂停的UI更新、线程或进程。

(1)、foreground生命周期状态会经常的改变,所以onResume()和onPause()方法做一些非常轻量级的工作,防止界面经常延迟等待。

(2)、恢复当Activity处于不活动状态时被挂起的暂停的UI更新、线程或进程。

Be aware that the system calls this method every time your activity comes into the foreground, including when it's created
for the first time. As such, you should implement
onResume()
to
initialize components that you release during
onPause()
and
perform any other initializations that must occur each time the activity enters the Resumed state (such as begin animations and initialize components only used while the activity has user focus).

5、onPause():Another
activity is taking focus (this activity is about to be "paused").

在Activity状态生存周期结束时调用。挂起不需要更新的UI更新、线程或者CPU密集的进程。

(1)、foreground生命周期状态会经常的改变,所以onResume()和onPause()方法做一些非常轻量级的工作,防止界面经常延迟等待。

(2)、系统调用该方法作为用户即将离开该Activity时的第一个迹象。该方法中通常应该处理当前用户回话中需要提交保存的改变(例如数据),因为用户可能不会再回到该界面。

(3)、保存需要存储到数据库中的持久化数据。

(4)、挂起不需要更新的UI更新、线程或者CPU密集的进程。

You should usually use the
onPause()
callback
to:

Stop animations or other ongoing actions that could consume CPU.
Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.

For example, if your application uses the
Camera
,
the
onPause()
method is a
good place to release it.
Generally, you should not use
onPause()
to
store user changes (such as personal information entered into a form) to permanent storage. The only time you should persist user changes to permanent storage within
onPause()
is
when you're certain users expect the changes to be auto-saved (such as when drafting an email). However, you should avoid performing CPU-intensive work during
onPause()
,
such as writing to a database, because it can slow the visible transition to the next activity (you should instead perform heavy-load shutdown operations during
onStop()
).

6、onStop()
The
activity is no longer visible (it is now "stopped")

在可见生存周期结束时调用。挂起不要的UI更新、线程或处理。当Activity不可见时,保存所有的编辑或者状态改变,因为调用这个方法后,进程可能会被终止。

(1)、unregister BroadcastReceiver

(2)、挂起不要的UI更新、线程或处理。

(3)、保存所有的编辑或者状态改变。

(4)、暂停或停止动画;

(5)、暂停或停止传感器监听器;

(6)、暂停或停止GPS查找;

(7)、暂停或停止定位器;

(8)、暂停或停止Service或者其他专门用于更新用户界面的进程,当UI不可见的时候更新它是没有意义的。

(9)、保存需要存储到数据库中的持久化数据。

When your activity
receives a call to the onStop() method, it's no longer visible and should release almost all resources that aren't needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory.
In extreme cases, the system might simply kill your app process without calling the activity's final onDestroy() callback, so it's important you use onStop() to release resources that might leak memory.

Although the onPause() method is called before onStop(), you should use onStop() to perform larger, more CPU intensive shut-down operations, such as writing information to a database.

When your activity is stopped, the Activity object is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to(leading up to:在…之前) the
Resumed state. The system also keeps track of the current state for each View in the layout, so if the user entered text into an EditText widget, that content is retained so you don't need to save and restore it.

7、onDestroy():The
activity is about to be destroyed.

在完整生存周期结束时调用。清理所有的资源,包括结束线程、关闭数据库连接等。

The system calls this method on your activity as the final signal that your activity instance is being completely removed
from the system memory.

Most apps don't need to implement this method because local class references are destroyed with the activity and your activity should perform most cleanup during
onPause()
and
onStop()
.
However, if your activity includes background threads that you created during
onCreate()
or
other long-running resources that could potentially(可能的,潜在的) leak(泄漏) memory if not properly closed, you should kill them during
onDestroy()
.

(1)、释放所有的持有的资源;

(2)、关闭开启的线程;

(3)、关闭数据库连接;

(4)、关闭网络连接。

8、onSaveInstanceState():保存Activity状态。

把UI状态改变保存到该方法中。

(1)、save
additional information


Although the default implementation of
onSaveInstanceState()
saves
useful information about your activity's UI, you still might need to override it to save additional
information
. For example, you might need to save member values that changed during the activity's life
(which might correlate to values restored in the UI, but the members that hold those UI values are not restored, by default).

如果实现了该方法来保存额外的信息,如果还想使用默认的onSaveInstanceState()方法保存Activity信息(推荐),首先要调用父类的onSaveInstanceState()方法。

(2)、因为onSaveInstanceState()方法不保证会一定执行,所以应只使用该方法来保存Ativity瞬时的、短暂的UI的状态信息,不用用该方法来保存持久化的数据,应该使用
onPause()
方法来保存持久化数据,例如存入数据库的数据。

(3)、屏幕旋转时保存Activity的信息。

9、onRestoreInstanceState()

用于恢复UI状态,只有当系统终止了该Activity后再次重新创建后,才会调用该方法。

(1)、通过
Bundle
参数保存的数据恢复被Kill掉的Activity的(onSaveInstanceState()方法中保存)状态信息。也可在onCreate()方法中恢复。

如下实现了该方法来恢复保存额外的信息,如果想使用默认的onRestoreInstanceState()方法来恢复保存Activity信息(推荐),首先要调用父类的onRestoreInstanceState()方法。

(2)、屏幕旋转时恢复onRestoreInstanceState()保存的Activity的信息。也可在onCreate()方法中恢复。

当然,以上的场景只是通常的情况下,每个回调函数中需要做的事情,具体的情况需要具体分析,在合适的时机调用对应的回调函数。

参考原文:http://developer.android.com/guide/components/activities.html#Lifecycle
http://developer.android.com/training/basics/activity-lifecycle/index.html

《Android 4 高级编程(第3版)》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: