Android:当我从最近的应用按钮关闭应用时,不会调用OnDestroy
当我们按下此按钮时,
When we press this button
我们看到我们没有关闭的应用,例如
We see the apps which we didn't close, like this
但是当我们要从此屏幕关闭应用程序时(图片下方),未调用onDestroy()方法,但应用程序已关闭。当应用程序以这种方式关闭时,我需要调用onDestroy()。我该怎么做?
But when we want to close an app from this screen (below image), the method onDestroy() isn't called, however the app is closed. I need to call onDestroy() when the app is closed in this way. How can I do this?
如Android文档中所述,不保证退出应用程序时将调用 onDestroy()
。
As specified in the Android documentation, it is not guaranteed that onDestroy()
will be called when exiting your application.
有些情况系统将在不调用此方法的情况下简单地终止活动的托管过程
"There are situations where the system will simply kill the activity's hosting process without calling this method"
https://developer.android.com/reference/android/app/Activity.html#onDestroy%28% 29
相反,您可以创建一项服务,当您的活动在其中运行的任务被销毁时,该服务将被通知。
Instead, you can create a service which will be notified when the Task your activities are running inside is destroyed.
创建服务类:
public class ClosingService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
// Handle application closing
fireClosingNotification();
// Destroy the service
stopSelf();
}
}
在清单中声明/注册您的服务(在应用程序标记,但在任何活动标记之外):
Declare / register your service in the manifest (within the application tag, but outside any activity tags):
<service android:name=".services.ClosingService"
android:stopWithTask="false"/>
指定 stopWithTask =false
将导致当从流程中删除任务时,将在您的服务中触发 onTaskRemoved()
方法。
Specifying stopWithTask="false"
will cause the onTaskRemoved()
method to be triggered in your service when the task is removed from the Process.
在这里在调用 stopSelf()
来销毁服务之前,可以运行你的结束应用程序逻辑。
Here you can run your closing application logic, before calling stopSelf()
to destroy the Service.