startActivityForResult
已過時生宛。官方建議使用 ActivityResultLauncher
替代。
首先吁断,創(chuàng)建 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);
});
}
/**
* 獲取上一個活動返回的結(jié)果
*/
private ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
switch (result.getResultCode()) {
case RESULT_OK:
String name = result.getData().getStringExtra("name");
Log.d(TAG, "收到的結(jié)果為: " + name);
break;
}
});
}