call method when program exits - onDestroy not reliable

丶灬走出姿态 提交于 2019-12-11 07:35:59

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4630531/call-method-when-program-exits-ondestroy-not-reliable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!