程序退出时的调用方法-onDestroy不可靠 [英] call method when program exits - onDestroy not reliable

查看:706
本文介绍了程序退出时的调用方法-onDestroy不可靠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过单击后退"按钮退出程序时执行一些功能. 现在,这可以通过onDestroy()来完成,该方法在每种情况下都可以工作,但一种情况下都可以.在某些情况下在退出程序时从另一个活动返回时,不会调用onDestroy.

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.

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

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.

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

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?

推荐答案

从策略上讲,使用onBackPressed().

从策略上重新考虑您的体系结构.编写良好的活动不应在乎是否调用onDestroy(),因为可以保证不会始终调用它.例如,Android可以在需要时终止您的进程(例如,内存极低的情况).您需要onDestroy()才能可靠地工作这一事实表明,有一些问题需要解决.

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.

这篇关于程序退出时的调用方法-onDestroy不可靠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆