Android api29中startActivityForResult提示已过时,应该变成registerForActivityResult,下面做了跳转携带数据和返回数据的处理。
//这个registerForActivityResult方法要写在Activity的onCreate方法里(在Activity创建的时候就要创建出来,不能等到使用的时候再创建,不然会报错LifecycleOwner com.xx.MainActivity@28b4e79 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.)。
ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
//获取返回的结果
String data = result.getData().getStringExtra("data");
Toast.makeText(activity, data, Toast.LENGTH_SHORT).show();
}
});
Intent intent = new Intent(JumpPage.this, NewWordActivity.class);
intent.putExtra("userId", "xxx");
intentActivityResultLauncher.launch(intent);
注意:这个registerForActivityResult方法要写在Activity的onCreate方法里(在Activity创建的时候就要创建出来,不能等到使用的时候再创建,不然会报错LifecycleOwner com.xx.MainActivity@28b4e79 is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.)。