— Android, Kotlin, registerForActivityResult — 1 min read
The registerForActivityResult method is a part of the Activity Result API, which was introduced as part of Android Jetpack. This API provides a more modular and consistent way to manage the flow of information between activities and fragments. It simplifies the process of dealing with different types of user interactions, such as picking a file, taking a picture, or requesting permissions.
Let's consider an example where you want to request a runtime permission, such as accessing the device's camera. With registerForActivityResult, you can streamline this process by defining a contract for the permission request and then handling the result in a concise and readable manner.
First, create a new instance of the ActivityResultContracts.RequestPermission class, passing in the permission you want to request:
1val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->2 if (isGranted) {3 // Permission is granted, continue with the desired operation4 } else {5 // Handle the scenario where the permission is denied6 }7}
Next, when you are ready to request the permission, you can use the requestPermissionLauncher to launch the permission request flow:
1requestPermissionLauncher.launch(Manifest.permission.CAMERA)
Another common use case is to receive a result from another activity, such as retrieving an image from the device's gallery. With registerForActivityResult, you can easily define a contract for this interaction and handle the result seamlessly.
Suppose you want to fetch an image from the device's gallery. You can create a contract using the ActivityResultContracts.GetContent() class:
1val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->2 // Handle the obtained content URI3 imageView.setImageURI(uri)4}
When you're ready to trigger the image selection process, you can simply call the launch method on getContent:
1getContent.launch("image/*")
By leveraging this modern approach, you can simplify the process of managing user interactions and streamline your project/codebase. Whether it's requesting permissions, capturing images, or handling other activity results, registerForActivityResult offers a cleaner and more organized way to incorporate these functionalities into your Android apps.