Android Activity 生命周期 - 所有这些方法的用途是什么?

发布于 2024-12-21 13:32:50 字数 253 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

我的鱼塘能养鲲 2024-12-28 13:32:50

请参阅活动生命周期(在 Android 开发人员中)。

在此处输入图像描述

onCreate()

首次创建活动时调用。这是你应该做的地方
所有常规静态设置:创建视图、将数据绑定到列表、
等等。此方法还为您提供了一个包含以下内容的 Bundle
活动之前的冻结状态(如果有)。一直关注
通过 onStart()。

onRestart()

在您的活动停止之后、开始之前调用
再次。始终跟随 onStart()

onStart()< /a>

当活动对用户可见时调用。其次是
onResume() 如果 Activity 进入前台。

onResume()

当活动开始与用户交互时调用。在此
点您的活动位于活动堆栈的顶部,用户
输入到它。始终跟随 onPause()。

onPause()

当活动进行时作为活动生命周期的一部分调用
进入背景,
但还没有被杀死。与 onResume() 相对应。
当 Activity B 在 Activity A 之前启动时,将在 A 上调用此回调。
B 在 A 的 onPause() 返回之前不会被创建,所以一定不要
在这里做任何冗长的事情。

onStop()

当您不再对用户可见时调用。接下来你会
接收 onRestart()、onDestroy() 或什么也不接收,具体取决于
稍后的用户活动。
请注意,在内存不足的情况下,可能永远不会调用此方法
系统没有足够的内存来保存您的活动
调用 onPause() 方法后运行的进程。

onDestroy()

您的活动被销毁之前收到的最后一个电话。这
可能会因为活动即将结束而发生(有人称为
finish()就可以了,或者因为系统暂时销毁了这个
活动实例以节省空间。您可以区分>这两种情况都使用 isFinishing() 方法。

当活动首次加载时,将调用如下事件:

onCreate()
onStart()
onResume()

当您单击“电话”按钮时,活动将转到后台并调用以下事件:

onPause()
onStop()

退出电话拨号器和以下事件将被调用:

onRestart()
onStart()
onResume()

当您单击后退按钮或尝试finish()活动时,事件将被调用,如下所示:

onPause()
onStop()
onDestroy()

<强><一href="http://docs.xamarin.com/android/tutorials/Activity_Lifecycle" rel="noreferrer">活动状态

Android 操作系统使用优先级队列来协助管理运行在设备。根据特定 Android 活动所处的状态,它将在操作系统中被分配一定的优先级。此优先级系统可帮助 Android 识别不再使用的活动,从而允许操作系统回收内存和资源。下图说明了活动在其生命周期内可以经历的状态:

这些状态可分为以下三个主要组:

活动或正在运行 - 如果活动处于活动状态,则被视为活动或正在运行前台,也称为活动堆栈的顶部。这被认为是 Android 活动堆栈中优先级最高的活动,因此只有在极端情况下才会被操作系统杀死,例如,如果该活动尝试使用比设备上可用的内存更多的内存,因为这可能会导致 UI变得反应迟钝。

已暂停 - 当设备进入睡眠状态,或者某个 Activity 仍然可见但被新的非全尺寸或透明 Activity 部分隐藏时,该 Activity 被视为已暂停。暂停的活动仍然存在,也就是说,它们维护所有状态和成员信息,并保持附加到窗口管理器。这被认为是 Android 活动堆栈中第二高优先级的活动,因此,只有在终止该活动能够满足保持活动/正在运行的活动稳定和响应所需的资源需求时,操作系统才会终止该活动。

已停止 - 被另一个活动完全遮挡的活动被视为已停止或处于后台。停止的活动仍然尝试尽可能长时间地保留其状态和成员信息,但停止的活动被认为是三个状态中优先级最低的,因此,操作系统将首先终止处于此状态的活动以满足资源需求更高优先级的活动。

*了解生命周期的示例活动**

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}

See it in Activity Lifecycle (at Android Developers).

Enter image description here

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().

onRestart():

Called after your activity has been stopped, prior to it being started
again. 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.

onResume():

Called when the activity will start interacting with the user. At this
point your activity is at the top of the activity stack, with user
input going to it. Always followed by onPause().

onPause ():

Called as part of the activity lifecycle when an activity is going
into the background,
but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A.
B will not be created until A's onPause() returns, so be sure to not
do anything lengthy here.

onStop():

Called when you are no longer visible to the user. You will next
receive either onRestart(), onDestroy(), or nothing, depending on
later user activity.
Note that this method may never be called, in low memory situations
where the system does not have enough memory to keep your activity's
process running after its onPause() method is called.

onDestroy():

The final call you receive before your activity is destroyed. This
can happen 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.

When the Activity first time loads the events are called as below:

onCreate()
onStart()
onResume()

When you click on Phone button the Activity goes to the background and the below events are called:

onPause()
onStop()

Exit the phone dialer and the below events will be called:

onRestart()
onStart()
onResume()

When you click the back button OR try to finish() the activity the events are called as below:

onPause()
onStop()
onDestroy()

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**

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}
失退 2024-12-28 13:32:50

活动有六种状态

  • 已创建
  • 已开始
  • 已恢复
  • 已暂停
  • 已停止 >
  • Destroyed

Activity 生命周期 有七个方法

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onRestart()
  • onDestroy()

活动生命周期

图表来源

情况

  • 打开应用程序时

     onCreate() --> onStart() --> onResume()
    
  • 按下后退按钮并退出应用程序时

     onPaused() --> onStop() --> onDestory()
    
  • 按下主页按钮时

     onPaused() --> onStop()
    
  • 按下主页按钮后,再次从最近的任务列表中打开应用程序或单击图标

     onRestart() --> onStart() --> onResume()
    
  • 当从通知栏或打开设置中打开应用程序时另一个应用程序

     onPaused() --> onStop()
    
  • 从另一个应用程序或设置中按下后退按钮,然后使用可以看到我们的应用程序

     onRestart() --> onStart() --> onResume()
    
  • 当屏幕上打开任何对话框时

     onPause()
    
  • 关闭对话框或对话框中的后退按钮后

    <前><代码> onResume()

  • 任何电话正在响铃并且用户在应用程序中

     onPause() --> onResume() 
    
  • 当用户按下电话的接听按钮时

     onPause()
    
  • 通话结束后

    <前><代码> onResume()

  • 手机屏幕关闭时

     onPaused() --> onStop()
    
  • 当屏幕重新打开时

     onRestart() --> onStart() --> onResume()
    

Activity has six states

  • Created
  • Started
  • Resumed
  • Paused
  • Stopped
  • Destroyed

Activity lifecycle has seven methods

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onRestart()
  • onDestroy()

activity life cycle

diagram source

Situations

  • When open the app

     onCreate() --> onStart() -->  onResume()
    
  • When back button pressed and exit the app

     onPaused() -- > onStop() --> onDestory()
    
  • When home button pressed

     onPaused() --> onStop()
    
  • After pressed home button when again open app from recent task list or clicked on icon

     onRestart() --> onStart() --> onResume()
    
  • When open app another app from notification bar or open settings

     onPaused() --> onStop()
    
  • Back button pressed from another app or settings then used can see our app

     onRestart() --> onStart() --> onResume()
    
  • When any dialog open on screen

     onPause()
    
  • After dismiss the dialog or back button from dialog

     onResume()
    
  • Any phone is ringing and user in the app

     onPause() --> onResume() 
    
  • When user pressed phone's answer button

     onPause()
    
  • After call end

     onResume()
    
  • When phone screen off

     onPaused() --> onStop()
    
  • When screen is turned back on

     onRestart() --> onStart() --> onResume()
    
场罚期间 2024-12-28 13:32:50

整个混乱的原因是 Google 选择了非直观的名称而不是如下所示的名称:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

活动图可以解释为:

enter image此处描述

The entire confusion is caused since Google chose non-intuivitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram can be interpreted as:

enter image description here

甜尕妞 2024-12-28 13:32:50

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.

  • Suppose you are using a calculator app. Three methods are called in
    succession to start the app.

onCreate() - - - > onStart() - - - > onResume()

  • When I am using the calculator app, suddenly a call comes the.
    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()

  • Now say I finish the conversation on the phone, the calculator
    activity comes to foreground from the background, so three methods
    are called in succession.

onRestart() - - - > onStart() - - - > onResume()

  • Finally, say I have finished all the tasks in calculator app, and I
    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
  • Running State
  • Paused State
  • Stopped state

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

孤独陪着我 2024-12-28 13:32:50

我喜欢这个问题及其答案,但到目前为止,还没有报道不太常用的回调,例如 onPostCreate()onPostResume( )。 Steve Pomeroy 尝试制作一个图表,其中包括这些内容以及它们与 Android Fragment 生命周期的关系,网址为 https://github.com/xxv/android-lifecycle。我修改了史蒂夫的大图表,使其仅包含活动部分,并将其格式化为信纸大小的一页打印输出。我已将其作为文本 PDF 发布在 https://github .com/code-read/android-lifecycle/blob/master/AndroidActivityLifecycle1.pdf 下面是其图像:

Android 活动生命周期

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 Activity Lifecycle

爱给你人给你 2024-12-28 13:32:50

从 Android 开发者页面,

onPause():

当系统即将开始恢复先前的活动时调用。
这通常用于将未保存的更改提交到持久数据,
停止动画和其他可能消耗CPU的东西等。
该方法的实现必须非常快,因为接下来
在此方法返回之前,活动不会恢复。其次是
如果 Activity 返回到前面,则使用 onResume() ,或者
onStop() 如果它对用户不可见。

停止():

当 Activity 对用户不再可见时调用,因为
另一项活动已经恢复并正在涵盖这一活动。这可能
发生的原因要么是一项新活动正在启动,要么是一项现有活动
正在被带到这个面前,或者这个正在被摧毁。
如果此活动返回,则紧接着 onRestart()
与用户交互,如果此活动消失,则使用 onDestroy()。

现在假设有三个Activity,并且从A到B,那么现在从B到C将调用A的onPause,然后将调用B的onPause和A的onStop。

暂停的活动将恢复,停止的活动将重新启动。

当你调用this.finish()时,onPause-onStop-onDestroy将会被调用。主要要记住的是:每当 Android 需要内存进行其他操作时,已暂停的活动就会停止,并且已停止的活动就会被销毁。

我希望它足够清楚。

From the Android Developers page,

onPause():

Called when the system is about to start resuming a previous activity.
This is typically used to commit unsaved changes to persistent data,
stop animations and other things that may be consuming CPU, etc.
Implementations of this method must be very quick because the next
activity will not be resumed until this method returns. Followed by
either onResume() if the activity returns back to the front, or
onStop() if it becomes invisible to the user.

onStop():

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

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.

迟月 2024-12-28 13:32:50

Android Activity 的生命周期是怎样的?

在android sdk框架中,每个android Activity(Window)都有生命周期方法。这意味着,当用户进入应用程序时,他可以看到在 onCreate() 生命周期方法中创建的 Activity。仅在 onCreate() 方法中附加在窗口中的布局。

Activity(Window) 具有以下生命周期状态:

Create - Activity is created. 
Start - Current activity gets started.
Resume - Current activity has been in resumed state.
Restart - Current activity has been in restarted.
Pause - Current activity has been in Paused state.
Stop - Current activity has been in stopped state.
destroy - Current activity has been in destroyed state.

为什么有这么多听起来相似的方法(onCreate()、onStart()、
onResume()) 在初始化期间调用,等等
(onPause(), onStop(), onDestroy()) 最后调用了吗?

用户第一次进入应用程序:

打开应用程序时,我们可以看到一个窗口(Activity)。 onCreate(创建)-> onStart(开始) -> onResume(恢复状态) 将被调用。

从后台关闭应用程序:

从后台关闭应用程序时,必须销毁 Activity 以释放一些内存。所以,onPause ->停止-> onDestroy 方法将被调用。

什么时候调用这些方法,以及如何正确使用它们?

启动应用程序:

当用户第一次进入某个 Activity 或应用程序时:

onCreate()

onStart() 

onResume()

当您从 android studio 运行该应用程序时:

onCreate()

onStart() 

onResume()

活动转换:

从第一个 Activity 移动时 -> ;第二个活动:

first_activity  : onPause()

second_activity : onCreate()

second_activity : onStart()

second_activity : onResume()

first_activity  : onStop()

从第二个活动移动时 ->第一个活动:

second_activity : onPause()

first_activity  : onRestart()

first_activity  : onStart()

first_activity  : onResume()

second_activity : onStop()

second_activity : onDestroy()

概览按钮

当用户单击概览按钮(硬件第三个按钮 - 最近列表)时:

onPause()

onStop()

用户关闭概览按钮后(或)用户从最近列表转到其他一些应用程序并返回到应用程序:

onRestart()

onStart()

onResume()

主页按钮:

当用户单击主页按钮时:

onPause()

onStop()

用户搜索主屏幕并单击应用程序图标返回活动:

onRestart()

onStart()

onResume()

用户接到电话:

当用户在活动中时,电话打来:

onPause()

onStop()

如果用户不参加通话,它会自动断开连接并返回活动(未接来电):

onRestart()

onStart()

onResume()

如果用户不参加通话:

N/A - 不会调用任何生命周期。

关机按钮:

当用户关闭按钮时:

onPause()

onStop()

当解锁设备时:

onRestart()

onStart()

onResume()

弹出对话框:

当弹出对话框出现时 - 不会调用生命周期

重新启动设备或关闭:

当用户重新启动或关闭设备时:

onPause()

onStop()

当用户单击主屏幕上的应用程序图标时:

onCreate()

onStart()

onResume()

What is the life cycle of an Android activity?

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:

Create - Activity is created. 
Start - Current activity gets started.
Resume - Current activity has been in resumed state.
Restart - Current activity has been in restarted.
Pause - Current activity has been in Paused state.
Stop - Current activity has been in stopped state.
destroy - Current activity has been in destroyed state.

Why are so many similar sounding methods (onCreate(), onStart(),
onResume()) called during initialization, and so many others
(onPause(), onStop(), onDestroy()) called at the end?

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.

When are these methods called, and how should they be used properly?

Starts the Application:

When user enter into an activity or application for the first time:

onCreate()

onStart() 

onResume()

When you run the app from android studio:

onCreate()

onStart() 

onResume()

Activity Transition:

When moving from First Activity -> Second Activity:

first_activity  : onPause()

second_activity : onCreate()

second_activity : onStart()

second_activity : onResume()

first_activity  : onStop()

When moving from Second Activity -> First Activity:

second_activity : onPause()

first_activity  : onRestart()

first_activity  : onStart()

first_activity  : onResume()

second_activity : onStop()

second_activity : onDestroy()

Overview Button:

When user clicks on Overview Button (hardware third button - recent list):

onPause()

onStop()

After user Dismiss the Overview Button (or) User went to some other apps from the recent list and coming back to the Application:

onRestart()

onStart()

onResume()

Home Button:

When user clicks on Home Button:

onPause()

onStop()

User search the home screen and clicks on application icon to coming back to the activity:

onRestart()

onStart()

onResume()

User gets Phone Call:

When user in an Activity, phone call came up:

onPause()

onStop()

If User doesn't attend the call, it disconnect automatically and back to activity (missed call):

onRestart()

onStart()

onResume()

If User doesn't attends the call:

N/A - No lifecycle will be called.

Power off Button:

When User power off the button:

onPause()

onStop()

When unlocks the device:

onRestart()

onStart()

onResume()

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:

onPause()

onStop()

When user clicks on app icon from the home screen:

onCreate()

onStart()

onResume()
故人的歌 2024-12-28 13:32:50

在高度评价的答案之上添加更多信息(添加了 KILLABLE 的附加部分和下一组方法,这些方法将在生命周期中调用):

来源:developer.android.com

在此处输入图像描述

请注意“可杀死”列上表——对于那些标记为可终止的方法,在该方法返回后,托管活动的进程可能会随时被系统终止,而无需执行其另一行代码。

因此,您应该使用 onPause() 方法将任何持久数据(例如用户编辑)写入存储。此外,在将 Activity 置于此类后台状态之前会调用方法 onSaveInstanceState(Bundle),这样您就可以将 Activity 中的任何动态实例状态保存到给定的 Bundle,如果需要重新创建活动,稍后将在 onCreate(Bundle) 中接收。

请注意,在 onPause() 中保存持久数据而不是 onSaveInstanceState(Bundle) 非常重要,因为后者不是生命周期回调的一部分,因此不会在其文档中描述的每种情况。

我想添加更多方法。这些未列为生命周期方法,但根据某些条件,它们将在生命周期期间被调用。根据您的要求,您可能必须在应用程序中实现这些方法才能正确处理状态。

onPostCreate(Bundle savedInstanceState)

当 Activity 启动完成时调用(在调用 onStart()onRestoreInstanceState(Bundle) 后)。

onPostResume()

活动恢复完成时调用(调用 onResume() 后)。

onSaveInstanceState(Bundle outState)

调用以在被终止之前从 Activity 检索每个实例的状态,以便可以在 onCreate(Bundle)onRestoreInstanceState(Bundle)(Bundle)中恢复状态通过此方法填充的内容将传递给两者)。

onRestoreInstanceState(Bundle savedInstanceState)

当 Activity 从之前保存的状态(在 savedInstanceState 中给出)重新初始化时,会在 onStart() 之后调用此方法。

我的应用程序代码使用所有这些方法:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(R.id.username);
        txtPassword=(EditText) findViewById(R.id.password);
        loginButton =  (Button)  findViewById(R.id.login);
        loginButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName",txtUserName.getText().toString());
        bundle.putString("password",txtPassword.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
       // IntentFilter
    }
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(R.id.txtView);
        txtView.setText(result);

        Intent sendIntent = new Intent();
        //sendIntent.setPackage("com.whatsapp");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Ravi","Main Start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Ravi","Main ReStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Ravi","Main Pause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Ravi","Main Resume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Ravi","Main Stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Ravi","Main OnDestroy");
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("Ravi","Main PostResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

登录活动:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        txtView = (TextView) findViewById(R.id.Result);
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
        intent.putExtra("result","Success");
        setResult(1,intent);
       // finish();
    }
}

输出:(暂停之前)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

输出:(从暂停恢复之后)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

请注意,即使没有将其引用为生命周期方法,也会调用 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

enter image description here

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 method onSaveInstanceState(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 given Bundle, to be later received in onCreate(Bundle) if the activity needs to be re-created.

Note that it is important to save persistent data in onPause() instead of onSaveInstanceState(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.

onPostCreate(Bundle savedInstanceState)

Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called).

onPostResume()

Called when activity resume is complete (after onResume() has been called).

onSaveInstanceState(Bundle outState)

Called to retrieve per-instance state from an activity before being killed so that the state can be restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method will be passed to both).

onRestoreInstanceState(Bundle savedInstanceState)

This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState.

My application code using all these methods:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private EditText txtUserName;
    private EditText txtPassword;
    Button  loginButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("Ravi","Main OnCreate");
        txtUserName=(EditText) findViewById(R.id.username);
        txtPassword=(EditText) findViewById(R.id.password);
        loginButton =  (Button)  findViewById(R.id.login);
        loginButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        Log.d("Ravi", "Login processing initiated");
        Intent intent = new Intent(this,LoginActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("userName",txtUserName.getText().toString());
        bundle.putString("password",txtPassword.getText().toString());
        intent.putExtras(bundle);
        startActivityForResult(intent,1);
       // IntentFilter
    }
    public void onActivityResult(int requestCode, int resultCode, Intent resIntent){
        Log.d("Ravi back result:", "start");
        String result = resIntent.getStringExtra("result");
        Log.d("Ravi back result:", result);
        TextView txtView = (TextView)findViewById(R.id.txtView);
        txtView.setText(result);

        Intent sendIntent = new Intent();
        //sendIntent.setPackage("com.whatsapp");
        sendIntent.setAction(Intent.ACTION_SEND);
        sendIntent.putExtra(Intent.EXTRA_TEXT, "Message...");
        sendIntent.setType("text/plain");
        startActivity(sendIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Ravi","Main Start");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Ravi","Main ReStart");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Ravi","Main Pause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Ravi","Main Resume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Ravi","Main Stop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Ravi","Main OnDestroy");
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        Log.d("Ravi","Main onPostCreate");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        Log.d("Ravi","Main PostResume");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }
}

Login Activity:

public class LoginActivity extends AppCompatActivity {

    private TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        txtView = (TextView) findViewById(R.id.Result);
        Log.d("Ravi","Login OnCreate");
        Bundle bundle = getIntent().getExtras();
        txtView.setText(bundle.getString("userName")+":"+bundle.getString("password"));
        //Intent  intent = new Intent(this,MainActivity.class);
        Intent  intent = new Intent();
        intent.putExtra("result","Success");
        setResult(1,intent);
       // finish();
    }
}

output: ( Before pause)

D/Ravi: Main OnCreate
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

output: ( After resume from pause)

D/Ravi: Main ReStart
D/Ravi: Main Start
D/Ravi: Main Resume
D/Ravi: Main PostResume

Note that onPostResume() is invoked even though it's not quoted as life cycle method.

羁客 2024-12-28 13:32:50

我按照上面的答案运行一些日志,这里是输出:

开始活动

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

停止活动

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

在我个人看来,只需要两个 onStart 和 onStop。

onResume 似乎出现在每次返回的实例中,而 onPause 出现在每次离开的实例中(关闭应用程序除外)。

I run some logs as per answers above and here is the output:

Starting Activity

On Activity Load (First Time)
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Reload After BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onCreate: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

OnMaximize(Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onRestart: 
D/IndividualChatActivity: onStart: 
D/IndividualChatActivity: onResume: 
D/IndividualChatActivity: onPostResume: 

Stopping The Activity

On BackPressed
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 
D/IndividualChatActivity: onDestroy: 

OnMinimize (Circle Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

OnMinimize (Square Button)
————————————————————————————————————————————————
D/IndividualChatActivity: onPause: 
D/IndividualChatActivity: onStop: 

Going To Another Activity
————————————————————————————————————————————————
D/IndividualChatActivity: onPause:
D/IndividualChatActivity: onStop: 

Close The App
————————————————————————————————————————————————
D/IndividualChatActivity: onDestroy: 

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文