Android Activity.finish() 方法到底在做什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10847526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:12:15  来源:igfitidea点击:

What is Activity.finish() method doing exactly?

androidactivity-lifecycleondestroyapplication-lifecycle

提问by Tal Kanel

I'm developing android applications for a while, and followed a lot of posts about activity life cycle, and application's life cycle.

我开发了一段时间的 android 应用程序,并关注了很多关于活动生命周期和应用程序生命周期的帖子。

I know Activity.finish()method calls somewhere in the way to Activity.onDestroy(), and also removing the activity from stack, and I guess it somehow points to operating system and garbage collector that he can "do his trick" and free the memory when it find it a good time doing so....

我知道Activity.finish()方法调用的某个地方Activity.onDestroy(),并且还从堆栈中删除了活动,我猜它以某种方式指向操作系统和垃圾收集器,他可以“做他的把戏”并在发现它的好时机时释放内存所以....

I came to this post - Is quitting an application frowned upon?and read Mark Murphy's answer.

我来到这篇文章 - 退出申请是否令人不悦?并阅读马克墨菲的回答。

It made me a bit confused about what exactly the finish()method actually does.

这让我对这个finish()方法究竟做了什么感到有些困惑。

Is there a chance I'll call finish()and onDestroy()won't be called?

有没有可能我会打电话finish()onDestroy()不会被打电话?

回答by K_Anas

When calling finish()on an activity, the method onDestroy()is executed. This method can do things like:

调用finish()活动时,将onDestroy()执行该方法。此方法可以执行以下操作:

  1. Dismiss any dialogs the activity was managing.
  2. Close any cursors the activity was managing.
  3. Close any open search dialog
  1. 关闭活动正在管理的任何对话框。
  2. 关闭活动正在管理的所有游标。
  3. 关闭任何打开的搜索对话框

Also, onDestroy()isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy()runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

此外,onDestroy()不是析构函数。它实际上并没有破坏对象。它只是一种基于特定状态调用的方法。因此,在超类onDestroy()运行和返回之后,您的实例仍然处于活动状态并且非常好* 。Android 会保留进程,以防用户想要重新启动应用程序,这使得启动阶段更快。该进程不会做任何事情,如果需要回收内存,该进程将被杀死

回答by Prakash

My 2 cents on @K_Anas answer. I performed a simple test on finish() method. Listed important callback methods in activity life cycle

我对@K_Anas 回答的 2 美分。我对 finish() 方法进行了一个简单的测试。列出Activity生命周期中重要的回调方法

  1. Calling finish() in onCreate(): onCreate() -> onDestroy()
  2. Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()
  3. Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()
  1. 在 onCreate() 中调用 finish():onCreate() -> onDestroy()
  2. 在 onStart() 中调用 finish() :onCreate() -> onStart() -> onStop() -> onDestroy()
  3. 在 onResume() 中调用 finish():onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

What I mean to say is that counterparts of the methods along with any methods in between are called when finish() is executed.

我的意思是说,当执行 finish() 时,将调用方法的对应物以及它们之间的任何方法。

eg:

例如:

 onCreate() counter part is onDestroy()
 onStart() counter part is onStop()
 onPause() counter part is onResume()

回答by Dan Wears Prada

Also notice if you call finish() after an intent you can't go back to the previous activity with the "back" button

另请注意,如果您在意图之后调用完成(),则无法使用“后退”按钮返回上一个活动

startActivity(intent);
finish();

回答by Kazekage Gaara

onDestroy()is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.

onDestroy()用于最终清理 - 释放您自己可以使用的资源,关闭打开的连接、读取器、写入器等。如果你不覆盖它,系统就会做它必须做的事情。

on the other hand, finish()just lets the system know that the programmer wants the current Activityto be finished. And hence, it calls up onDestroy()after that.

另一方面,finish()只是让系统知道程序员希望当前Activity完成。因此,它onDestroy()在那之后调用。

Something to note:

需要注意的一点:

it isn't necessary that onlya call to finish()triggers a call to onDestroy(). No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activitythat are needed to be freed.

没有必要调用 来finish()触发调用onDestroy()。不可以。我们知道,android 系统如果觉得有当前需要的资源需要Activity释放,则可以自由杀死活动。

回答by Udit Kapahi

Finish() method will destroy the current activity. You can use this method in cases when you dont want this activity to load again and again when the user presses back button. Basically it clears the activity from the.current stack.

Finish() 方法将销毁当前活动。如果您不希望在用户按下后退按钮时一次又一次地加载此活动,您可以使用此方法。基本上它会从 .current 堆栈中清除活动。

回答by Brandon Lim

In addition to @rommex answer above, I have also noticed that finish()does queue the destruction of the Activity and that it depends on Activity priority.

除了上面的@rommex 回答之外,我还注意到finish()确实将 Activity 的销毁排入队列,并且它取决于 Activity 的优先级。

If I call finish()after onPause(), I see onStop(), and onDestroy()immediately called.

如果我finish()在之后打电话onPause(),我看到了onStop(),并onDestroy()立即打电话。

If I call finish()after onStop(), I don't see onDestroy()until 5 minutes later.

如果我finish()在 之后打电话onStop(),我会onDestroy()在 5 分钟后才看到。

From my observation, it looks like finish is queued up and when I looked at the adb shell dumpsys activity activitiesit was set to finishing=true, but since it is no longer in the foreground, it wasn't prioritized for destruction.

根据我的观察,它看起来像完成排队,当我看到adb shell dumpsys activity activities它被设置为finishing=true,但由于它不再在前台,它没有优先销毁。

In summary, onDestroy()is never guaranteed to be called, but even in the case it is called, it could be delayed.

总之,onDestroy()永远不能保证被调用,但即使在它被调用的情况下,它也可能被延迟。

回答by CoderOfTheNight

Various answers and notes are claiming that finish() can skip onPause() and onStop() and directly execute onDestroy(). To be fair, the Android documentation on this (http://developer.android.com/reference/android/app/Activity.html) notes "Activity is finishing or being destroyed by the system" which is pretty ambiguous but might suggest that finish() can jump to onDestroy().

各种答案和笔记都声称finish() 可以跳过onPause() 和onStop() 直接执行onDestroy()。公平地说,关于此的 Android 文档 ( http://developer.android.com/reference/android/app/Activity.html) 指出“活动正在完成或被系统销毁”,这是非常模棱两可的,但可能表明Finish() 可以跳转到 onDestroy()。

The JavaDoc on finish() is similarly disappointing (http://developer.android.com/reference/android/app/Activity.html#finish()) and does not actually note what method(s) are called in response to finish().

Finish() 上的 JavaDoc 同样令人失望(http://developer.android.com/reference/android/app/Activity.html#finish())并且实际上并没有注意到响应完成调用了哪些方法()。

So I wrote this mini-app below which logs each state upon entry. It includes a button which calls finish() -- so you can see the logs of which methods get fired. This experiment would suggested that finish() does indeedalso call onPause() and onStop(). Here is the output I get:

所以我在下面写了这个迷你应用程序,它在进入时记录每个状态。它包括一个调用finish() 的按钮——这样你就可以看到哪些方法被触发的日志。这个实验表明finish()确实也调用了onPause() 和onStop()。这是我得到的输出:

2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO﹕ User just clicked button to initiate finish() 
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onStop 
2170-2170/? D/LIFECYCLE_DEMO﹕ INSIDE: onDestroy

package com.mvvg.apps.lifecycle;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class AndroidLifecycle extends Activity {

    private static final String TAG = "LIFECYCLE_DEMO";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "INSIDE: onCreate");
        setContentView(R.layout.activity_main);
        LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
        Button button = new Button(this);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
                        Toast.LENGTH_SHORT).show();
                Log.d(TAG, "User just clicked button to initiate finish()");
                finish();
            }

        });

        layout.addView(button);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "INSIDE: onStart");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "INSIDE: onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "INSIDE: onDestroy");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "INSIDE: onPause");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "INSIDE: onResume");
    }

}

回答by Meryan

@user3282164 According to the Activitylife-cycle it should go through onPause()-> onStop()-> onDestroy()upon calling finish().

@user3282164 根据Activity生命周期,它应该通过onPause()-> onStop()->onDestroy()在调用finish().

The diagram does not show any straight path from [Activity Running] to [onDestroy()] caused by the system.

图中没有显示onDestroy()由系统引起的从 [Activity Running] 到 [ ] 的任何直线路径。

onStop()doc says "Note that this method may neverbe 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."

onStop()文档说“请注意,在内存不足的情况下,系统没有足够的内存来保持活动进程在调用 onPause() 方法后继续运行,请注意,可能永远不会调用此方法。

回答by rommex

My study shows that finish()method actually places some destruction operations in the queue, but the Activity is not destroyed immediately. The destruction is scheduled though.

我的研究表明,该finish()方法实际上在队列中放置了一些销毁操作,但不会立即销毁 Activity。不过销毁是按计划进行的。

For example, if you place finish()in onActivityResult()callback, while onResume()has yet to run, then first onResume()will be executed, and only after that onStop()and onDestroy()are called.

例如,如果你把finish()onActivityResult()回调,而onResume()目前尚未运行,则首先onResume()将被执行,只有经过onStop()onDestroy()被调用。

NOTE: onDestroy()may not be called at all, as stated on the documentation.

注意:onDestroy()可能根本不会被调用,如文档中所述

回答by anand krish

calling finish in onCreate() will not call onDestroy() directly as @prakash said. The finish()operation will not even begin until you return control to Android.

在 onCreate() 中调用 finish 不会像@prakash 所说的那样直接调用 onDestroy() 。在finish()您将控制权返回给 Android 之前,该操作甚至不会开始。

Calling finish() in onCreate(): onCreate() -> onStart() -> onResume(). If user exit the app will call -> onPause() -> onStop() -> onDestroy()

onCreate() 中调用 finish() :onCreate() -> onStart() -> onResume()。如果用户退出应用程序将调用-> onPause() -> onStop() -> onDestroy()

Calling finish() in onStart(): onCreate() -> onStart() -> onStop() -> onDestroy()

onStart() 中调用 finish() :onCreate() -> onStart() -> onStop() -> onDestroy()

Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

onResume() 中调用 finish() :onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

For further reference check look at this oncreate continuous after finish& about finish()

如需进一步参考检查,请查看此oncreate 连续完成后关于完成()