Android startActivityForResult 替代方案:startActivity 和 registerForActivityResult
在新的 Android 版本中,建议使用 startActivity 和 registerForActivityResult 来代替 startActivityForResult。具体使用方法如下:
- 使用
startActivity启动 Activity:
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
- 在调用
startActivity之前,使用registerForActivityResult注册一个ActivityResultCallback回调:
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// 处理返回结果
}
});
- 在需要接收返回结果的地方,使用
launcher.launch()方法启动 Activity:
Intent intent = new Intent(this, SecondActivity.class);
launcher.launch(intent);
- 在 SecondActivity 中,通过
setResult方法返回结果:
Intent intent = new Intent();
intent.putExtra('key', 'value');
setResult(Activity.RESULT_OK, intent);
finish();
AI 优化版
原文地址:https://www.cveoy.top/t/topic/nvvK 著作权归作者所有。请勿转载和采集!