在Android中,我有一些活动,比如说A、B、C.

在A中,我使用此代码打开B:

Intent intent = new Intent(this, B.class);
startActivity(intent);

在B中,我使用以下代码打开C:

Intent intent = new Intent(this, C.class);
startActivity(intent);

当用户点击C中的一个按钮时,我想返回a并清除后堆栈(同时关闭B和C).因此,当用户使用后退按钮B和C不会出现时,我一直在try 以下操作:

Intent intent = new Intent(this, A.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent);

但是,如果我在返回活动A时使用后退按钮,B和C仍然会出现,我如何才能避免这种情况?

推荐答案

try 添加FLAG_ACTIVITY_NEW_TASK,如FLAG_ACTIVITY_CLEAR_TOP文档中所述:

此启动模式还可用于 配合使用效果良好 FLAG_ACTIVITY_NEW_TASK:如果使用 启动任务的根活动,它 将使任何当前正在运行的 将该任务实例添加到 前景,然后将其清除到其 根状态.这特别有用, 例如,在启动 通知中的活动 经理.

因此,启动A的代码应该是:

Intent intent = new Intent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent);
CurrentActivity.this.finish(); // if the activity running has it's own context


// view.getContext().finish() for fragments etc.

Android相关问答推荐

未解析的引用:背景 colored颜色

错误:无法解析Symbol@style/Theme. Androidstudio in AndroidManifest.html for Kotlin Android Development''

如何将Hilt添加到Android Studio中的Kotlin项目中?

使用不同的Google帐户登录

如何在Reaction Native中显示Google Map iFrame?

房间DB:UPSERT返回什么?

无法在Jetpack Compose中显示Admob原生广告

避免在按下肯定按钮时自动取消AlertDialog

无法使用MenuItemColors.Copy()

无法将非静态方法与Frida挂钩

用于小部件泄漏警告的伙伴对象中的Kotlin Lateinit

如何使用Jetpack Compose实现此底表?

Android系统应用程序启用编程以太网网络共享

如何从sqlite数据库中检索数据到碎片android?

Lateinit变量结果始终以kotlin格式未初始化

如何在Jetpack Compose中实现前后动画?

是否可以在 compose 中使用三次贝塞尔曲线进行动画?

在 react native 中设置 react-native-paper 组件的样式

如何使用jetpack compose实现布局,其中图标在列布局上是绝对位置

如何在 kotlin 的 android room DB 中设置一对多关系