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

使用Activity Result API获取结果时返回null及RESULT_CANCELED

问题解决:Fragment向启动方Activity返回结果始终为RESULT_CANCELED

可能的原因及解决方案

1. Activity B的启动模式或任务栈问题

如果Activity B的启动模式是singleTask/singleInstance,或者启动时带有FLAG_ACTIVITY_NEW_TASK标志,会导致Activity B处于独立任务栈,此时setResult()无法将结果传递给原任务栈的Activity A。

解决步骤:

  • 检查AndroidManifest.xml中Activity B的配置,确保launchMode为默认的standard(如果显式设置了其他模式,改回standard):
    <activity
        android:name=".ActivityB"
        android:launchMode="standard">
        <!-- 其他配置 -->
    </activity>
    
  • 启动Activity B时,移除Intent中的FLAG_ACTIVITY_NEW_TASK标志:
    val deepLinkIntent = Intent(Intent.ACTION_VIEW, yourDeepLinkUri)
    // 移除可能存在的NEW_TASK标志
    deepLinkIntent.flags = deepLinkIntent.flags and Intent.FLAG_ACTIVITY_NEW_TASK.inv()
    resultLauncher.launch(deepLinkIntent)
    

2. 结果被Activity B的生命周期代码覆盖

如果Activity B的onPause/onStop/onDestroy等方法中,有调用setResult(Activity.RESULT_CANCELED)的逻辑,会覆盖Fragment设置的结果。

解决步骤:

  • 排查Activity B的所有生命周期方法,确保没有重置结果的代码。

3. 优化Fragment设置结果的方式

避免Fragment直接操作Activity的结果,通过Activity提供统一方法来处理,减少意外:

  • 在Activity B中添加方法:
    fun finishWithResult(resultCode: Int, data: Intent?) {
        setResult(resultCode, data)
        finish()
    }
    
  • 在Fragment中调用该方法:
    val resultIntent = Intent().apply {
        putExtra("RESULT_KEY", "Success from Fragment")
    }
    (requireActivity() as ActivityB).finishWithResult(Activity.RESULT_OK, resultIntent)
    

内容的提问来源于stack exchange,提问作者kartik srivastava

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:12:34