在 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/