首先需要androidx.activity:activity的版本大于1.2.0才能使用launch替换。
修改build.gradle下的依赖库为1.3.0或以上版本。
implementation 'androidx.appcompat:appcompat:1.4.0'
A页面跳转
private ActivityResultLauncher<Intent> launcher;
Intent intent = new Intent(this, B.class);
intent.putExtra("data", "传递数据");
launcher.launch(intent);
B页面接收值
String data = getIntent().getStringExtra("data");
B页面点击或返回结束页面
Intent intent = new Intent();
intent.putExtra("result","回调数据");
setResult(Activity.RESULT_OK,intent);
finish();
A页面回调接收数据
launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode() == Activity.RESULT_OK){
String data = result.getData().getStringExtra("result");
}
}
});