startActivityForResult() deprecated alternative and using it outside activity class

We use startActivityForResult() to send and receive data between activities, in almost of our android projects.
But recently startActivityForResult() method is deprecated in AndroidX. Android came up with ActivityResultCallback (also called Activity Results API) as an alternative for it.
Normal way to send and receive data by startActivityForResult()
To implement it by Activity Results API you can replace this code by following
Steps to use Activity Results API
Step 1: You just have to create an ActivityResultLauncher and pass following parameters handle onActivityResult in it as shown above.
- ActivityResultContract<I,O>, where I is input and O is output
- A callback for onActivityResult.
Step 2: Now create your intent accordingly and call launch function on your launcher and pass your intent in it as shown above to start activity for result.
That’s it you’re done with it.
Now in some cases we implement startActivityForResult() outside our activity class.
We can implement ActivityResultLauncher outside activity class simply by passing ActivityResultRegistry in the constructor of class in which you are using and creating your launcher.
Let’s take a case where we have a dialog for adding images. We have a made a different class to show and handle dialog actions.
So the action here also remains the same, we just need to pass registry as a parameter in constructor. Then create your launcher as shown above and create an intent and launch it by launcher.
That’s it we’re done!
Additionally it comes it number of options with StartActivityForResult.

You can use it to request multiple permissions at once, take pictures and videos directly and many more just by changing the generic param of ActivityResultLauncher according to action.