java - Android:当我从最近的应用程序按钮关闭应用程序时,不会调用 OnDestroy

标签 java android ondestroy close-application

当我们按下这个按钮时

我们看到我们没有关闭的应用程序,像这样

但是当我们想从这个屏幕(下图)关闭应用程序时,不会调用 onDestroy() 方法,但是应用程序会关闭。当应用程序以这种方式关闭时,我需要调用 onDestroy() 。我怎样才能做到这一点?

最佳答案

如 Android 文档中所述,不保证退出应用程序时会调用 onDestroy()

"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

相反,您可以创建一个服务,当您的 Activity 在其中运行的任务被销毁时,该服务将收到通知。

创建服务类:

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();
    }
}

在 list 中声明/注册您的服务(在应用程序标签内,但在任何 Activity 标签外):

<service android:name=".services.ClosingService"
             android:stopWithTask="false"/>

指定 stopWithTask="false" 将导致当从 Process 中删除任务时在您的服务中触发 onTaskRemoved() 方法。

在调用 stopSelf() 销毁服务之前,您可以在此处运行关闭应用程序逻辑。

关于java - Android:当我从最近的应用程序按钮关闭应用程序时,不会调用 OnDestroy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41744933/

相关文章:

java - Color.RGBToHSV 类型不匹配 : cannot convert from void to float[]

java - 如何在 Slick2D 中对字体大小进行动画处理,而无需每次渲染创建新的字体实例?

java - 检查java中的单词变体(词干)

java - 什么对创建对象的时间影响最大​​?

java - 如何获取标题 onPageFinished() (webview)?

android - 防止 Activity 在按下后退按钮时被破坏

java - 在应用程序销毁时保存变量不起作用

java - 为什么我的 ListView 在我的 Fragment 方向改变后变为空?

android - 如何获取 AttributeSet 属性

android被销毁时是否有任何 View 回调?