registerForActivityResult

‘startActivityForResult(android.content.Intent, int)’ is deprecated
startActivityForResult方法提示过时,官方推荐使用registerForActivityResult写法

一、A页面

在A页面中先调用registerForActivityResult,获取ActivityResultLauncher

private ActivityResultLauncher<Intent> mBackType;

mBackType = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent data = result.getData();
                if (data != null) {
                    String backType = data.getStringExtra("backType");
                    LogUtils.d("backType: " + backType);
                }
            }
        });

跳转的地方调用launch

                Intent intent = new Intent(this, MedicationInfoActivity.class);
                intent.putExtra("type", MedicationType.MEDICATION_GLU);
                mBackType.launch(intent);

二、B页面

在B页面中设置返回数据

        Intent intent = getIntent();
        intent.putExtra("backType", mType);
        setResult(RESULT_OK, intent);
        finish();

猜你喜欢

转载自blog.csdn.net/Billy_Zuo/article/details/129713663
今日推荐