2.3.5返回数据给上一个活动
startActivityForResult()启用,使用registerForActivityResult()代替,
报错:“is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED”需要将registerForActivityResult()写在onCreate()中,表示在生命周期STARTED之前调用
public class FirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result)
{
int resultCode = result.getResultCode();
if(resultCode==RESULT_OK)
{
String returnData = result.getData().getStringExtra("data_return");
Log.d("FirstActivity",returnData);
}
}
});
setContentView(R.layout.first_layout);
Button button1 = (Button)findViewById(R.id.button_1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view)
{
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intentActivityResultLauncher.launch(intent);
}
});
}