简体   繁体   English

Android - 服务 - 使用强制停止时未调用 onDestroy() 方法

[英]Android - Service - onDestroy() method not called when using Force Stop

When I stop a service using the stop button under the Running Services tab, the method onDestroy() is called.当我使用 Running Services 选项卡下的停止按钮停止服务时,会调用 onDestroy() 方法。

But when I force stop the application, onDestroy() is never called.但是当我强制停止应用程序时,永远不会调用 onDestroy()。

Any explainations about this?对此有何解释?

or maybe a solution to fire onDestroy() when force-stopped?或者在强制停止时触发 onDestroy() 的解决方案?

When your force stop an app, exactly that happens - It is Force Stopped.当您强制停止应用程序时,就会发生这种情况 - 它是强制停止。 No warning, no callbacks, just stopped.没有警告,没有回调,只是停止了。 The entire process is killed, and none of the running components (Activities, Services etc) are given any warning.整个进程被杀死,并且没有任何正在运行的组件(活动、服务等)被发出任何警告。

There is absolutely no guarantee that onDestroy() will be called.绝对不能保证会调用onDestroy() Move any application critical code into onPause() , which is called under most circumstances.将任何应用程序关键代码移到onPause()中,在大多数情况下都会调用它。

From the documentation :文档中:

Once the activity is created, onPause() is the last method that's guaranteed to be called before the process can be killed... onStop() and onDestroy() might not be called.创建活动后, onPause()是保证在进程被终止之前调用的最后一个方法... onStop()onDestroy()可能不会被调用。 Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage.因此,您应该使用onPause()将关键的持久数据(例如用户编辑)写入存储。

To reiterate this point, Force Stop isn't intended to be graceful and exit the app in a caring manner.重申这一点,强制停止并不是为了优雅地退出应用程序。 If you have critical code that must be run each time app finishes you need to run it in onPause() .如果您有每次应用程序完成时必须运行的关键代码,则需要在onPause()中运行它。

When the application gets force stop, Process.killProcess() is called but not onDestroy() function.当应用程序强制停止时,会调用 Process.killProcess() 但不会调用 onDestroy() 函数。 Go through this link.通过这个链接。 You will get some idea.你会有一些想法。 Android force Stop callback to application? Android强制停止回调到应用程序?

I am assuming you have code that you want to execute in onDestroy() referring to your line:我假设您有要在onDestroy()中执行的代码,引用您的行:

"or maybe a solution to fire onDestroy() when force-stopped?" “或者可能是在强制停止时触发 onDestroy() 的解决方案?”

The Service method public void onTaskRemoved(Intent rootIntent) is what you are looking for, it will be called when the app is force-stopped. Service方法public void onTaskRemoved(Intent rootIntent)是您正在寻找的,它将在应用程序被强制停止时调用。

我知道这是一个老问题,但我遇到了同样的问题,就我而言,我使用的是绑定服务,所以即使在调用stopSelf()之后,Android 也不会调用onDestroy()方法,为了强制它我需要调用unbindService()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM