I've got a simple ActivityResultLauncher implementation, where I can select an image from the gallery:
ActivityResultLauncher<Intent> actResLauncher;
actResLauncher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(),this);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
actResLauncher.launch(intent);
And the result:
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode()== Activity.RESULT_OK){
}
}
The issue is with this code is that I rely on the predefined Resultcodes like Activity.RESULT_OK or Activity.RESULT_CANCELED. Is there a way to pass custom Requestcodes when launching the intent?
First of all, you do not need onActivityResult()
. That way was old. You now have launchers for specific purposes. So no more request codes
You now do it like below.
Create a function like this:
ActivityResultLauncher<String> imageActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.GetContent(),
uri ->
//do something with uri
});
And then wherever you want to launch this, just write:
imageActivityResultLauncher.launch("image/*");
For more details refer to this stackoverflow answer https://stackoverflow.com/a/63654043/12555686