Android Activity 生命周期 - 所有这些方法的用途是什么?
Android Activity 的生命周期是怎样的?为什么在初始化期间调用了这么多听起来相似的方法(onCreate()
、onStart()
、onResume()
),以及这么多其他方法( onPause()
、onStop()
、onDestroy()
) 最后调用了吗?
这些方法什么时候被调用,以及应该如何正确使用它们?
What is the life cycle of an Android activity? Why are so many similar sounding methods (onCreate()
, onStart()
, onResume()
) called during initialization, and so many others (onPause()
, onStop()
, onDestroy()
) called at the end?
When are these methods called, and how should they be used properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
请参阅活动生命周期(在 Android 开发人员中)。
onCreate():
onRestart():
onStart()< /a>:
onResume():
onPause():
onStop():
onDestroy():
当活动首次加载时,将调用如下事件:
当您单击“电话”按钮时,活动将转到后台并调用以下事件:
退出电话拨号器和以下事件将被调用:
当您单击后退按钮或尝试finish()活动时,事件将被调用,如下所示:
<强><一href="http://docs.xamarin.com/android/tutorials/Activity_Lifecycle" rel="noreferrer">活动状态
Android 操作系统使用优先级队列来协助管理运行在设备。根据特定 Android 活动所处的状态,它将在操作系统中被分配一定的优先级。此优先级系统可帮助 Android 识别不再使用的活动,从而允许操作系统回收内存和资源。下图说明了活动在其生命周期内可以经历的状态:
这些状态可分为以下三个主要组:
活动或正在运行 - 如果活动处于活动状态,则被视为活动或正在运行前台,也称为活动堆栈的顶部。这被认为是 Android 活动堆栈中优先级最高的活动,因此只有在极端情况下才会被操作系统杀死,例如,如果该活动尝试使用比设备上可用的内存更多的内存,因为这可能会导致 UI变得反应迟钝。
已暂停 - 当设备进入睡眠状态,或者某个 Activity 仍然可见但被新的非全尺寸或透明 Activity 部分隐藏时,该 Activity 被视为已暂停。暂停的活动仍然存在,也就是说,它们维护所有状态和成员信息,并保持附加到窗口管理器。这被认为是 Android 活动堆栈中第二高优先级的活动,因此,只有在终止该活动能够满足保持活动/正在运行的活动稳定和响应所需的资源需求时,操作系统才会终止该活动。
已停止 - 被另一个活动完全遮挡的活动被视为已停止或处于后台。停止的活动仍然尝试尽可能长时间地保留其状态和成员信息,但停止的活动被认为是三个状态中优先级最低的,因此,操作系统将首先终止处于此状态的活动以满足资源需求更高优先级的活动。
*了解生命周期的示例活动**
See it in Activity Lifecycle (at Android Developers).
onCreate():
onRestart():
onStart():
onResume():
onPause ():
onStop():
onDestroy():
When the Activity first time loads the events are called as below:
When you click on Phone button the Activity goes to the background and the below events are called:
Exit the phone dialer and the below events will be called:
When you click the back button OR try to finish() the activity the events are called as below:
Activity States
The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:
These states can be broken into three main groups as follows:
Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.
Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.
Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.
*Sample activity to understand the life cycle**
活动有六种状态
Activity 生命周期 有七个方法
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
onDestroy()
图表来源
情况
打开应用程序时
按下后退按钮并退出应用程序时
按下主页按钮时
按下主页按钮后,再次从最近的任务列表中打开应用程序或单击图标
当从通知栏或打开设置中打开应用程序时另一个应用程序
从另一个应用程序或设置中按下后退按钮,然后使用可以看到我们的应用程序
当屏幕上打开任何对话框时
关闭对话框或对话框中的后退按钮后
<前><代码> onResume()
任何电话正在响铃并且用户在应用程序中
当用户按下电话的接听按钮时
通话结束后
<前><代码> onResume()
手机屏幕关闭时
当屏幕重新打开时
Activity has six states
Activity lifecycle has seven methods
onCreate()
onStart()
onResume()
onPause()
onStop()
onRestart()
onDestroy()
diagram source
Situations
When open the app
When back button pressed and exit the app
When home button pressed
After pressed home button when again open app from recent task list or clicked on icon
When open app another app from notification bar or open settings
Back button pressed from another app or settings then used can see our app
When any dialog open on screen
After dismiss the dialog or back button from dialog
Any phone is ringing and user in the app
When user pressed phone's answer button
After call end
When phone screen off
When screen is turned back on
整个混乱的原因是 Google 选择了非直观的名称而不是如下所示的名称:
活动图可以解释为:
The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:
The Activity Diagram can be interpreted as:
ANDROID LIFE-CYCLE
有七种方法来管理Android应用程序的生命周期:
回答所有这些方法的用途:
让我们看一个简单的场景,了解这些方法的调用顺序将帮助我们清楚地了解使用它们的原因。
连续启动应用程序。
onCreate()
- - - >onStart()
- - - >onResume()
计算器活动转到后台,另一个活动说。
处理调用来到前台,现在有两个方法
纷纷叫道。
onPause()
- - - >onStop()
Activity从后台来到前台,所以三种方法
纷纷被召唤。
onRestart()
- - - >onStart()
- - - >onResume()
想要退出该应用程序。连续调用另外两个方法。
onStop()
- - - >onDestroy()
有四种状态活动可能存在:
开始状态涉及:< /strong>
创建一个新的 Linux 进程,为其分配新的内存新的 UI 对象,并设置整个屏幕。所以大部分工作都涉及到这里了。
运行状态涉及:
它是当前屏幕上的活动(状态)。该状态单独处理诸如在屏幕上打字、触摸和触摸等事情。单击按钮。
暂停状态涉及:
当 Activity 不在前台而是在后台时,则称该 Activity 处于暂停状态。
停止状态涉及:
停止的活动只能通过重新启动才能进入前台,并且可以在任何时间点被销毁。
活动管理器以这样的方式处理所有这些状态,即使在将新活动添加到现有活动的情况下,用户体验和性能也始终处于最佳状态
ANDROID LIFE-CYCLE
There are seven methods that manage the life cycle of an Android application:
Answer for what are all these methods for:
Let us take a simple scenario where knowing in what order these methods are called will help us give a clarity why they are used.
succession to start the app.
onCreate()
- - - >onStart()
- - - >onResume()
The calculator activity goes to the background and another activity say.
Dealing with the call comes to the foreground, and now two methods are
called in succession.
onPause()
- - - >onStop()
activity comes to foreground from the background, so three methods
are called in succession.
onRestart()
- - - >onStart()
- - - >onResume()
want to exit the app. Futher two methods are called in succession.
onStop()
- - - >onDestroy()
There are four states an activity can possibly exist:
Starting state involves:
Creating a new Linux process, allocating new memory for the new UI objects, and setting up the whole screen. So most of the work is involved here.
Running state involves:
It is the activity (state) that is currently on the screen. This state alone handles things such as typing on the screen, and touching & clicking buttons.
Paused state involves:
When an activity is not in the foreground and instead it is in the background, then the activity is said to be in paused state.
Stopped state involves:
A stopped activity can only be bought into foreground by restarting it and also it can be destroyed at any point in time.
The activity manager handles all these states in such a way that the user experience and performance is always at its best even in scenarios where the new activity is added to the existing activities
我喜欢这个问题及其答案,但到目前为止,还没有报道不太常用的回调,例如 onPostCreate() 或 onPostResume( )。 Steve Pomeroy 尝试制作一个图表,其中包括这些内容以及它们与 Android Fragment 生命周期的关系,网址为 https://github.com/xxv/android-lifecycle。我修改了史蒂夫的大图表,使其仅包含活动部分,并将其格式化为信纸大小的一页打印输出。我已将其作为文本 PDF 发布在 https://github .com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf 下面是其图像:
I like this question and the answers to it, but so far there isn't coverage of less frequently used callbacks like onPostCreate() or onPostResume(). Steve Pomeroy has attempted a diagram including these and how they relate to Android's Fragment life cycle, at https://github.com/xxv/android-lifecycle. I revised Steve's large diagram to include only the Activity portion and formatted it for letter size one-page printout. I've posted it as a text PDF at https://github.com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf and below is its image:
从 Android 开发者页面,
onPause():
停止():
现在假设有三个Activity,并且从A到B,那么现在从B到C将调用A的onPause,然后将调用B的onPause和A的onStop。
暂停的活动将恢复,停止的活动将重新启动。
当你调用
this.finish()
时,onPause-onStop-onDestroy将会被调用。主要要记住的是:每当 Android 需要内存进行其他操作时,已暂停的活动就会停止,并且已停止的活动就会被销毁。我希望它足够清楚。
From the Android Developers page,
onPause():
onStop():
Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.
The paused Activity gets a Resume and Stopped gets Restarted.
When you call
this.finish()
, onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.I hope it's clear enough.
在android sdk框架中,每个android Activity(Window)都有生命周期方法。这意味着,当用户进入应用程序时,他可以看到在 onCreate() 生命周期方法中创建的 Activity。仅在 onCreate() 方法中附加在窗口中的布局。
Activity(Window) 具有以下生命周期状态:
用户第一次进入应用程序:
打开应用程序时,我们可以看到一个窗口(Activity)。 onCreate(创建)-> onStart(开始) -> onResume(恢复状态) 将被调用。
从后台关闭应用程序:
从后台关闭应用程序时,必须销毁 Activity 以释放一些内存。所以,onPause ->停止-> onDestroy 方法将被调用。
启动应用程序:
当用户第一次进入某个 Activity 或应用程序时:
当您从 android studio 运行该应用程序时:
活动转换:
从第一个 Activity 移动时 -> ;第二个活动:
从第二个活动移动时 ->第一个活动:
概览按钮:
当用户单击概览按钮(硬件第三个按钮 - 最近列表)时:
用户关闭概览按钮后(或)用户从最近列表转到其他一些应用程序并返回到应用程序:
主页按钮:
当用户单击主页按钮时:
用户搜索主屏幕并单击应用程序图标返回活动:
用户接到电话:
当用户在活动中时,电话打来:
如果用户不参加通话,它会自动断开连接并返回活动(未接来电):
如果用户不参加通话:
N/A - 不会调用任何生命周期。
关机按钮:
当用户关闭按钮时:
当解锁设备时:
弹出对话框:
当弹出对话框出现时 - 不会调用生命周期
重新启动设备或关闭:
当用户重新启动或关闭设备时:
当用户单击主屏幕上的应用程序图标时:
In android sdk framework, Every android Activity(Window) having lifecycle methods. That means, when user enter into an application, he can see the Activity thats been created in onCreate() lifecycle method. Layouts attached in the window in onCreate() method only.
Activity(Window) has following lifecycle states:
First time user enter into an application:
When opening the application, we can see one Window(Activity). onCreate (created) -> onStart(started) -> onResume(resume state) will be called.
Close the application from background:
when closing the application from the background, activity has to be destroyed to free up some memory. So, onPause -> onStop -> onDestroy methods will be called.
Starts the Application:
When user enter into an activity or application for the first time:
When you run the app from android studio:
Activity Transition:
When moving from First Activity -> Second Activity:
When moving from Second Activity -> First Activity:
Overview Button:
When user clicks on Overview Button (hardware third button - recent list):
After user Dismiss the Overview Button (or) User went to some other apps from the recent list and coming back to the Application:
Home Button:
When user clicks on Home Button:
User search the home screen and clicks on application icon to coming back to the activity:
User gets Phone Call:
When user in an Activity, phone call came up:
If User doesn't attend the call, it disconnect automatically and back to activity (missed call):
If User doesn't attends the call:
N/A - No lifecycle will be called.
Power off Button:
When User power off the button:
When unlocks the device:
Pop Up Dialog:
When pop up dialog came up - No lifecycle will be called
Restart Device or Switch off:
When user restarts or switch off device:
When user clicks on app icon from the home screen:
在高度评价的答案之上添加更多信息(添加了 KILLABLE 的附加部分和下一组方法,这些方法将在生命周期中调用):
来源:developer.android.com
请注意“可杀死”列上表——对于那些标记为可终止的方法,在该方法返回后,托管活动的进程可能会随时被系统终止,而无需执行其另一行代码。
因此,您应该使用
onPause()
方法将任何持久数据(例如用户编辑)写入存储。此外,在将 Activity 置于此类后台状态之前会调用方法onSaveInstanceState(Bundle)
,这样您就可以将 Activity 中的任何动态实例状态保存到给定的Bundle
,如果需要重新创建活动,稍后将在onCreate(Bundle)
中接收。请注意,在
onPause()
中保存持久数据而不是onSaveInstanceState(Bundle)
非常重要,因为后者不是生命周期回调的一部分,因此不会在其文档中描述的每种情况。我想添加更多方法。这些未列为生命周期方法,但根据某些条件,它们将在生命周期期间被调用。根据您的要求,您可能必须在应用程序中实现这些方法才能正确处理状态。
我的应用程序代码使用所有这些方法:
登录活动:
输出:(暂停之前)
输出:(从暂停恢复之后)
请注意,即使没有将其引用为生命周期方法,也会调用
onPostResume()
。Adding some more info on top of highly rated answer (Added additional section of KILLABLE and next set of methods, which are going to be called in the life cycle):
Source: developer.android.com
Note the "Killable" column in the above table -- for those methods that are marked as being killable, after that method returns the process hosting the activity may be killed by the system at any time without another line of its code being executed.
Because of this, you should use the
onPause()
method to write any persistent data (such as user edits) to storage. In addition, the methodonSaveInstanceState(Bundle)
is called before placing the activity in such a background state, allowing you to save away any dynamic instance state in your activity into the givenBundle
, to be later received inonCreate(Bundle)
if the activity needs to be re-created.Note that it is important to save persistent data in
onPause()
instead ofonSaveInstanceState(Bundle)
because the latter is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.I would like to add few more methods. These are not listed as life cycle methods but they will be called during life cycle depending on some conditions. Depending on your requirement, you may have to implement these methods in your application for proper handling of state.
My application code using all these methods:
Login Activity:
output: ( Before pause)
output: ( After resume from pause)
Note that
onPostResume()
is invoked even though it's not quoted as life cycle method.我按照上面的答案运行一些日志,这里是输出:
开始活动
停止活动
在我个人看来,只需要两个 onStart 和 onStop。
onResume 似乎出现在每次返回的实例中,而 onPause 出现在每次离开的实例中(关闭应用程序除外)。
I run some logs as per answers above and here is the output:
Starting Activity
Stopping The Activity
In my personal opinion only two are required onStart and onStop.
onResume seems to be in every instance of getting back, and onPause in every instance of leaving (except for closing the app).