Java Android:finish() 总是调用 onDestroy() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19891969/
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-12 21:05:42  来源:igfitidea点击:

Android: Will finish() ALWAYS call onDestroy()?

javaandroidondestroyactivity-finish

提问by Xander

Simple question: can you be sure that finish()will call onDestroy()? I haven't found any confirmation on this.

简单的问题:你能确定finish()会打电话onDestroy()吗?我还没有找到任何确认。

采纳答案by CommonsWare

Simple question: can you be sure that finish() will call onDestroy()?

简单的问题:你能确定finish() 会调用onDestroy() 吗?

First, this answer assumes that you are referring to Android's Activityclass and its finish()method and onDestroy()lifecycle method.

首先,这个答案假设您指的是 Android 的Activity类及其finish()方法和onDestroy()生命周期方法。

Second, it depends upon your definition of "sure":

其次,这取决于您对“确定”的定义:

  • Your process could be terminated in between finish()and onDestroy(), for reasons independent of whatever is triggering the call to finish()

  • A device manufacturer or ROM modder could introduce some screwy change that would break the connection between finish()and onDestroy()

  • The battery could go dead in between finish()and onDestroy()

  • Etc.

  • 您的进程可能会在finish()和之间终止onDestroy(),原因与触发对finish()

  • 设备制造商或 ROM 修改器可能会引入一些奇怪的更改,这会破坏finish()onDestroy()

  • 该电池能够在两者之间走死finish()onDestroy()

  • 等等。

Third, finish()does not callonDestroy(). You can tell that by reading the source code. finish()usually triggers a callto onDestroy().

三、finish()onDestroy()。您可以通过阅读源代码了解这一点。finish()通常会触发一个电话onDestroy()

Generally speaking, finish()will eventually result in onDestroy()being called.

一般来说,finish()最终会导致onDestroy()被调用。

回答by Aniket Thakur

No you cannot be sure!

不,你不能确定!

Calling finish() generally triggers onDestroy() as per the Activity life cycle but you cannot rely on it. Specifically not for saving your data. Documentationclearly says

调用 finish() 通常会根据 Activity 生命周期触发 onDestroy() ,但您不能依赖它。特别是不用于保存您的数据。文档清楚地说明

do not count on this method being called as a place for saving data!