SecondActivity中
public class SecondActivity extends AppCompatActivity {
private static final String TAG = "SecondActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Button btnQuit = findViewById(R.id.btnQuit);
btnQuit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: ");
Intent intent = new Intent();
intent.putExtra("data_return", "返回的数据");
setResult(RESULT_OK, intent);
finish();
}
});
}
}
MainActivity中
ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
Log.d(TAG, "onActivityResult: data = " + result.getData().getStringExtra("data_return"));
}
}
});
btnSecond.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 1);
launcher.launch(intent);
标签:弃用,SecondActivity,registerForActivityResult,void,intent,startActivityForResult,O
From: https://www.cnblogs.com/jaronpeng/p/17314801.html