Android:当我从最近的应用按钮关闭应用时,不会调用OnDestroy [英] Android: OnDestroy isn't called when I close the app from the recent apps button

查看:1757
本文介绍了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.

这篇关于Android:当我从最近的应用按钮关闭应用时,不会调用OnDestroy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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