程序退出时调用方法 - onDestroy 不可靠

发布于 2024-10-10 22:32:36 字数 320 浏览 0 评论 0原文

我想在通过按后退按钮退出程序时执行一些功能。 现在,这是由 onDestroy() 完成的,它适用于除一种情况之外的所有情况。在某些情况下,当退出程序时从另一个活动返回时,不会调用 onDestroy。

我知道理论上 onDestroy 应该只在 Android 由于内存不足而关闭应用程序时调用,但对我来说,onDestroy 始终有效,并且只有在非常特殊的情况下才不会。

使用 onPause 或 onStop 不起作用,因为我只想在程序退出时调用该函数,而不是在调用另一个活动时调用该函数。

那么最后一种方法是捕获后退按钮单击并在那里调用该函数吗?或者还有其他解决办法吗?

I want to execute some functions when the program is exited by hitting the back button.
This is now done by onDestroy() which works in every case but one. When coming back from another activity in some cases on exiting the program, onDestroy is not called.

I know that in theory onDestroy should only be called when Android closes the app due to low memory, but for me, onDestroy works always and only in a very special case it does not.

Using onPause or onStop does not work because I only want to call the function when the program is exited but not when just another activity is called.

So is the last way to catch the back-button-click and call the function there? Or is there any other solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

你的他你的她 2024-10-17 22:32:36

从战术上讲,请使用onBackPressed()

从战略上讲,重新考虑您的架构。编写良好的活动不应该关心 onDestroy() 是否被调用,因为它保证不会总是被调用。例如,Android 可以随时终止您的进程(例如,内存极低的情况)。事实上,您需要 onDestroy() 才能可靠地工作,这表明存在应该解决的问题。

Tactically, use onBackPressed().

Strategically, reconsider your architecture. A well-written activity should not care if onDestroy() is called, as it is guaranteed to NOT always be called. For example, Android can terminate your process whenever it wants (e.g., extreme low memory conditions). The fact that you need onDestroy() to work reliably suggests there are problems that should be resolved.

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