我们可以使用“registerForActivityResult”发送和获取“requestCode”吗?

D T*_*D T 11 android

因为startActivityForResult已被弃用。所以我替换startActivityForResultregisterForActivityResult

这是我的代码:

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        // There are no request codes
                        //Intent data = result.getData();
                        //doSomeOperations();
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

因为我调用了多个 Activity:

旧版本:

 Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
 startActivityForResult(myinten, 111);

Intent myinten = new Intent(MainActivity.this, MainActivity3.class);
startActivityForResult(myinten, 222);
Run Code Online (Sandbox Code Playgroud)

新版本:

Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
someActivityResultLauncher.launch(myinten);

Intent myinten = new Intent(MainActivity.this, MainActivity3.class);
someActivityResultLauncher.launch(myinten);
Run Code Online (Sandbox Code Playgroud)

我们可以使用“registerForActivityResult”发送和获取“requestCode”吗?

小智 20

为每次启动创建一个新的 ActivityResultLauncher,或者在启动活动时在包中传递您自己的标识符。

 ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent intent = result.getData();
                        //get your "requestCode" here with switch for "SomeUniqueID"
                    }
                }
            });
Run Code Online (Sandbox Code Playgroud)

启动活动


Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
myinten.putExtra("requestCode", "SomeUniqueID");
someActivityResultLauncher.launch(myinten);


Run Code Online (Sandbox Code Playgroud)

返回的活动

Intent intent = new Intent();
//these should not be hard coded, but retrieved from the intent which created this activity
intent.putExtra("requestCode", "SomeUniqueID");
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案在创建并打算启动画廊系统应用程序等系统活动时不起作用。Intent 被覆盖任何额外的值,它将返回 null 对象 Intentintent = result.getData(); 请问这种情况的一些解决方案吗? (2认同)