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

取消StartActivityForResult时如何获取Intent数据?手动取消后能否获取?

处理StartActivityForResult取消后的Intent数据获取问题

Great question! Let's break this down into two clear scenarios: handling intentional cancellations where you can pass data, and working around cases where the result Intent is missing entirely.

1. 获取主动取消时的Intent数据(常规场景)

Whether you're using the old startActivityForResult() API or the newer Activity Result API, you can retrieve data after a cancellation—as long as you explicitly set the result Intent in the launched Activity before finishing it.

旧API (startActivityForResult())

In the launched Activity, when the user triggers a cancellation (like tapping a cancel button or pressing the back key), manually set RESULT_CANCELED along with your data-carrying Intent:

// TargetActivity: Handle cancel button click
findViewById(R.id.btn_cancel).setOnClickListener(v -> {
    Intent resultIntent = new Intent();
    resultIntent.putExtra("cancel_reason", "User tapped cancel");
    resultIntent.putExtra("partial_input", "Half-filled form data");
    setResult(Activity.RESULT_CANCELED, resultIntent);
    finish();
});

// Override back key to pass data too
@Override
public void onBackPressed() {
    Intent resultIntent = new Intent();
    resultIntent.putExtra("cancel_reason", "Back button pressed");
    setResult(Activity.RESULT_CANCELED, resultIntent);
    super.onBackPressed();
}

Then in your original Activity's onActivityResult():

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == MY_REQUEST_CODE) {
        if (resultCode == Activity.RESULT_CANCELED) {
            if (data != null) {
                String reason = data.getStringExtra("cancel_reason");
                String partialInput = data.getStringExtra("partial_input");
                // Process the data here
            }
        }
    }
}

The logic for the launched Activity stays the same. In your original Activity, register a callback to receive the result:

// OriginalActivity: Register the result callback
val activityLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_CANCELED) {
        result.data?.let { intent ->
            val reason = intent.getStringExtra("cancel_reason")
            val partialInput = intent.getStringExtra("partial_input")
            // Handle the canceled data
        }
    }
}

// Launch the target Activity
activityLauncher.launch(Intent(this, TargetActivity::class.java))

2. 手动取消后无法获取Intent数据:有没有补救办法?

If the launched Activity finishes without calling setResult() (e.g., a bug, or the system kills it due to low memory), result.data will be null. But you can still retrieve data with these workarounds:

方案1:使用ViewModel共享数据(Same App, Recommended)

If both Activities are in the same app, use a shared ViewModel to pass data without relying on the result Intent:

// Shared ViewModel class
class SharedCancelViewModel : ViewModel() {
    val canceledData = MutableLiveData<CancelData>() // CancelData is your custom data class
}

// TargetActivity: Store data when canceling
val viewModel = ViewModelProvider(requireActivity()).get(SharedCancelViewModel::class.java)
viewModel.canceledData.value = CancelData("Unexpected cancel", "User's partial input")
finish()

// OriginalActivity: Observe the shared data
val viewModel = ViewModelProvider(this).get(SharedCancelViewModel::class.java)
viewModel.canceledData.observe(this) { data ->
    // Access the canceled data here
}

方案2:用SharedPreferences Persist Data

Save the data to SharedPreferences in the launched Activity, then read it in the original Activity's callback:

// TargetActivity: Save data on cancel
SharedPreferences sp = getSharedPreferences("cancel_data_store", MODE_PRIVATE);
sp.edit()
   .putString("reason", "No result Intent set")
   .putString("partial_input", "User's unfinished work")
   .apply();
finish();

// OriginalActivity: Retrieve data when result is missing
if (resultCode == Activity.RESULT_CANCELED && result.getData() == null) {
    SharedPreferences sp = getSharedPreferences("cancel_data_store", MODE_PRIVATE);
    String reason = sp.getString("reason", null);
    String partialInput = sp.getString("partial_input", null);
    // Process the data, then clear it to avoid conflicts next time
    sp.edit().clear().apply();
}

方案3:Local Database (For Complex Data)

For large or structured data, use a local database like Room to temporarily store the data. The original Activity can query the database in the result callback and delete the temporary record afterward.

⚠️ Important Notes:

  • Avoid static variables for data passing—they cause memory leaks, especially if the Activity is destroyed.
  • When using SharedPreferences or databases, add unique identifiers (like a request ID) to avoid overwriting data from multiple launches.
  • If the system kills the launched Activity, it can save state in onSaveInstanceState(), but the original Activity can't access this state directly—rely on pre-persisted data instead.

内容的提问来源于stack exchange,提问作者Shashikant Yadav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:34:53