android - 当我们使用 FLAG_ACTIVITY_NEW_TASK 清除 Activity 堆栈时,OnDestroy 不会触发

标签 android android-activity back-stack

在 android 中,假设我有以下 Activity

Activity A -> Activity B -> Activity C -> Activity D

在某些场景中,我必须直接从 Activity D 导航到 Activity A(示例:注销场景)。在这种情况下,我使用下面的方法来清除 backstack 并导航到 Activity A。这只不过是杀死并再次打开应用程序。

        // Go to LoginActivity.java
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlag(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();

绝对工作正常!毫无疑问。

我现在需要什么?

当我从 Activity D 导航到 A 时(使用 FLAG_ACTIVITY_NEW_TASK。)我期望 Activity D、C 的 OnDestroy() 方法, B 执行。但目前尚未触发/触发。

为什么我期望调用 OnDestroy 方法?

清除后退堆栈时,我需要从所有 Activity 中调用一个 trackevent(de-register) 方法。例如:来自 Activity D、C 和 B。因此,我希望调用 OnDestroy 方法(或者任何方法也可以)。请帮我解决这个问题?

最佳答案

根据文档

FLAG_ACTIVITY_CLEAR_TOP: If an instance of the Activity to be launched already exists in the back stack, destroy any other Activity on top of it and route the Intent to that existing instance. When used in conjunction with FLAG_ACTIVITY_NEW_TASK, this flag locates any existing instances of the Activity in any task and brings it to the foreground.

您可以通过将 Intent.FLAG_ACTIVITY_CLEAR_TASK 替换为 Intent.FLAG_ACTIVITY_CLEAR_TOP 来实现。

修改后的代码:

Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

因此,返回堆栈 onDestroy 方法中的所有 Activity 都将按照插入的顺序调用,包括您的 LoginActivity 的 onDestroy 方法。

关于android - 当我们使用 FLAG_ACTIVITY_NEW_TASK 清除 Activity 堆栈时,OnDestroy 不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53722795/

相关文章:

android - 更改 Android 日历 View 的样式

android 整数值从一个 Activity 传递到另一个问题

android - 我需要根据事件日期显示和隐藏复选框

android - 清除导航 Controller 的完整后台堆栈

android - 使用 Android Navigation Architecture Component 重新创建 backstack

android - 使用 RecyclerView 跨越多个列

android - 在 android 中退出时清除应用程序缓存

android - 如何压缩与 fragment 标签匹配的后台 fragment ?

android - android中的WAP推送消息

java - 形成和执行 if 语句的问题