在新的 Android 版本中,建议使用 startActivity 和 registerForActivityResult 来代替 startActivityForResult。具体使用方法如下:

  1. 使用 startActivity 启动 Activity:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
  1. 在调用 startActivity 之前,使用 registerForActivityResult 注册一个 ActivityResultCallback 回调:
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                // 处理返回结果
            }
        });
  1. 在需要接收返回结果的地方,使用 launcher.launch() 方法启动 Activity:
Intent intent = new Intent(this, SecondActivity.class);
launcher.launch(intent);
  1. 在 SecondActivity 中,通过 setResult 方法返回结果:
Intent intent = new Intent();
intent.putExtra('key', 'value');
setResult(Activity.RESULT_OK, intent);
finish();