startActivityForResult
已过时。官方建议使用 ActivityResultLauncher
替代。
首先,创建 ActivityResultLauncher 对象,然后使用 ActivityResultLauncher 对象的 launch 方法启动新活动。
public class MainActivity extends BaseActivity {
private Button mButton;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.initView();
}
/**
* 初始化View
*/
private void initView() {
// 按钮
mButton = findViewById(R.id.main_start_btn);
mButton.setOnClickListener(view -> {
// 启动新活动
Intent intent = new Intent(this, HomeActivity.class);
this.activityResultLauncher.launch(intent);
});
}
/**
* 获取上一个活动返回的结果
*/
private ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
switch (result.getResultCode()) {
case RESULT_OK:
String name = result.getData().getStringExtra("name");
Log.d(TAG, "收到的结果为: " + name);
break;
}
});
}