Home > Net >  Can we to send & get "requestCode" with "registerForActivityResult"?
Can we to send & get "requestCode" with "registerForActivityResult"?

Time:01-05

Because startActivityForResult is deprecated. So I replace startActivityForResult to registerForActivityResult

This is my code:

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();
                    }
                }
            });

Because i call to multi Activity:

Old Version:

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

Intent myinten = new Intent(MainActivity.this, MainActivity3.class);
startActivityForResult(myinten, 222);

New Version:

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

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

Can we to send & get "requestCode" with "registerForActivityResult"?

CodePudding user response:

Either create a new ActivityResultLauncher for each launch or pass your own identifier in a bundle when launching the activity.

 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"
                    }
                }
            });

Launch Activity


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


Activity which returns

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();
  •  Tags:  
  • Related