程序退出时调用方法 - onDestroy 不可靠
我想在通过按后退按钮退出程序时执行一些功能。 现在,这是由 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从战术上讲,请使用
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 needonDestroy()
to work reliably suggests there are problems that should be resolved.