You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中3个Activity基于startActivityForResult实现特定返回流程

Android Activity 跳转场景实现方案

场景1:正常返回栈流程(C→B→A)

这是Android默认的返回栈行为,只要启动Activity时使用默认的standard启动模式,无需额外代码即可实现:

  • 从A启动B:startActivity(new Intent(A.this, B.class))
  • 从B启动C:startActivity(new Intent(B.this, C.class))
    此时按返回键,系统会自动将当前Activity出栈,依次回到上一个页面。

如果场景1失效,检查以下两点:

  • 确认A、B、C在Manifest中的launchMode是否被修改为singleTask/singleInstance等特殊模式,改回默认即可
  • 检查是否在B或C中重写了onBackPressed()但未调用super.onBackPressed(),补上该方法即可恢复默认返回逻辑

场景2:C提交后直接跳转至A并销毁B

以下是两种常用实现方式:

方法1:Intent标记清除中间栈

在C的提交操作完成后,启动A时添加特定标记,同时销毁当前C:

// C中提交成功后的代码
Intent intent = new Intent(C.this, A.class);
// 清除A之上的所有Activity(即B)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// 若A已在栈中,复用现有实例而非重建
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
// 销毁当前C页面
finish();

如果不需要复用A实例,可去掉FLAG_ACTIVITY_SINGLE_TOP,此时会销毁原A并创建新实例。

方法2:ActivityResultAPI回传结果(适合需传递数据的场景)

如果需要从C向A回传提交结果,可通过ActivityResultAPI实现:

  1. 在A中注册启动B的Launcher:
// A中的代码
private ActivityResultLauncher<Intent> launcher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK) {
            Intent data = result.getData();
            // 处理C回传的数据
        }
    }
);

// 启动B时调用
launcher.launch(new Intent(A.this, B.class));
  1. 在B中注册启动C的Launcher:
// B中的代码
private ActivityResultLauncher<Intent> cLauncher = registerForActivityResult(
    new ActivityResultContracts.StartActivityForResult(),
    result -> {
        if (result.getResultCode() == RESULT_OK) {
            // 收到C的结果后,销毁B并将结果回传给A
            setResult(RESULT_OK, result.getData());
            finish();
        }
    }
);

// 启动C时调用
cLauncher.launch(new Intent(B.this, C.class));
  1. 在C中提交完成后设置结果并销毁自身:
// C中提交成功后的代码
Intent data = new Intent();
data.putExtra("submit_status", "success");
setResult(RESULT_OK, data);
finish();

此方式会让C先销毁回到B,B收到结果后立即销毁回到A,最终实现C提交后直接跳转至A且B被销毁的效果。

方法3:Jetpack Navigation实现(若使用导航组件)

如果项目使用Jetpack Navigation,可在导航图中给C到A的action配置属性:

<action
    android:id="@+id/action_c_to_a"
    app:destination="@id/a"
    app:popUpTo="@id/a"
    app:popUpToInclusive="false" />
  • popUpTo="@id/a":跳转到A时,弹出栈中A之上的所有页面(即B)
  • popUpToInclusive="false":保留现有A实例(设为true则销毁原A并重建)

在C中调用跳转:

// Kotlin代码
findNavController().navigate(R.id.action_c_to_a)

内容的提问来源于stack exchange,提问作者Compose Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 00:54:12