ActivityResult API Android…

Image for post
Image for post

Today we will learn about ActivityResult API, which makes the life of Android developers a lot easier to manage the permissions, and inter-activity communication.

  • Currently if we need some data from child activity or another activity started by host activity we use startActivityForResult and onActivityResult
  • Second use case is permissions, if you ever implemented the asking permissions ex. access media files, etc. You got it.

Now we will see how the above mentioned use-case’s👆 implementation got more easier with ActivityResult API

First things First :

  • Dependencies : Add the 👇 following 2 dependencies in your app level build.gradle file

Request permissions : There are 2 ways to request permissions provided by this API.

ActivityResultContracts.RequestPermission()) : If you want to request single permission this contract will do the job for you.

  • Create ActivityRequestLauncher with RequestPermisison contract

Lambda in the following code 👇 will execute when the request finishes, you can call it onRequestPermissionsResult.

It returns Boolean in this case based on if permission is granted or not

Image for post
Image for post
  • Now that’s it you are good to go to request any permisison and it will do the job for you
Image for post
Image for post
  • There are many other prebuilt contract provided by API that you can use directly like RequestPermisison. Check the Reference section to learn more about.

If you want to request multiple permissions use the following contract:

Image for post
Image for post

Here result 👆 is of type Map<String,Boolean>, which have permission name as a key and value based on if permision is granted or not

Now we will see, How we can use this API to get data from the child activity.

  • We will create custom contract which extend the ActivityResultContract<Input, Output>()

Input : If you need to send some data

Output : Result that you expect from the activity that you started for result

  • Here 👇 we have created custom contract which take Int as input and gives us result of type String
Image for post
Image for post
  • There are two methods that we need to override :
  • Let’s use this contract :
Image for post
Image for post

Written by

Mobile Software Engineer at Manulife. GDG Organizer at GDG Montreal.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store