Android 检测应用程序何时关闭
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10387774/
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
Detect when application is closed
提问by JLouis
I want to know when the app is closed, because I need to erase a Database when the user shutdown the app, just in the moment when the user close the app is the right moment to erase the SQLite Database, how can I detect this?
我想知道应用程序何时关闭,因为我需要在用户关闭应用程序时擦除数据库,就在用户关闭应用程序的那一刻是擦除 SQLite 数据库的正确时机,我该如何检测?
采纳答案by jcxavier
Supposing you don't finish()
your main activity, clearing your database inside the onDestroy()
method of that activity might be the closest of what you want to accomplish. As has been pointed in the comments, refer to http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle.
假设你不是finish()
你的主要活动,在该onDestroy()
活动的方法中清除你的数据库可能是你想要完成的最接近的事情。正如评论中指出的那样,请参阅http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle。
回答by Chris Stratton
This is a flawed design idea, which reflects a misunderstanding of the system - when the process overall dies, it's dead, meaning your code is no longer running.
这是一个有缺陷的设计思想,它反映了对系统的误解——当进程整体死亡时,它就死了,这意味着你的代码不再运行。
You can do some tracking and have the last onDestory()'d activity do the cleanup as a courtesy, but don't assume that it will always actually happen (the method is not alwayscalled). If having a stale copy is a problem, clean it up on the next run.
出于礼貌,您可以进行一些跟踪并让最后一个 onDestory() 活动进行清理,但不要假设它总是会实际发生(该方法并不总是被调用)。如果有一个陈旧的副本是一个问题,请在下次运行时清理它。
That said, you can try using the ndk to provide a handler for process termination signals, but still I wouldn't count on it working in all cases. The limited potential to gain any sound functionality from this would probably not justify the effort unless you are already familiar with the concepts involved.
也就是说,您可以尝试使用 ndk 为进程终止信号提供处理程序,但我仍然不指望它在所有情况下都能正常工作。除非您已经熟悉所涉及的概念,否则从中获得任何声音功能的有限潜力可能无法证明这一努力的合理性。
And do not for a minute mistake cleaning up for a security mechanism, as the file is there while your app is running, and would remain if your app terminated in an unexpected way.
并且不要为安全机制清理一分钟的错误,因为该文件在您的应用程序运行时就在那里,如果您的应用程序以意外方式终止,它将保留下来。