
1. Overview
In this article, we will discuss the Activity Result API, an alternative to the deprecated startActivityForResult + onActivityResult methods.
Android introduced the Activity Result APIs as a major change in the androidx.activity:activity:1.2.0
and androidx.activity:activity-ktx:1.2.0
releases.
This API improves code readability, avoids using request code, improves type safety.
2. Old way using startActivityForResult and onActivityResult
In the old way, we perform the following to get the required result from another activity:
- Create an Intent
- Pass intent and also request code to
startActivityForResult
method. The request code returned in theonActivityResult
to identify the request (Intent) for which the result came back. - Register onActivityResult to retrieve the result
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == RESULT_OK && requestCode == 1001) { } } val intent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY) startActivityForResult(intent, 1001)
3. Alternative to deprecated startActivityForResult
The Activity Result APIs provide the registerForActivityResult
in place of startActivityForResult +
onActivityResult
.
The registerForActivityResult
method takes the following two parameters and returns ActivityResultLauncher
as output:
1. ActivityResultContracts
A contract defines the type of action or interaction (Intent) requested from an activity. After getting the result from the activity, it then produces the output of a particular type that makes calling activity for result type-safe.
A collection of standard ActivityResultContracts available for use. Among the contracts available, the StartActivityForResult
contract is the replacement to the startActivityForResult
.
2. ActivityResultCallback
The callback is to be called once the activity result is available. Whatever code you plan to write in your old onActivityResult
method must be placed here.
For example, the below registerForActivityResult
method takes the ActivityResultContracts.StartActivityForResult
as contract and then returns the ActivityResultLauncher
as output.
var resultLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { // parse result and perform action } }
Once you have the ActivityResultLauncher
, you can launch the activity using the launch
method:
val intent = Intent(context, TargetActivity::class.java) resultLauncher.launch(intent)
Notice that we haven’t passed any request code here as registerForActivityResult
automatically takes care of everything.
4. Conclusion
To sum up, we have discussed the Activity Result API available from androidx 1.2.0 releases as an alternative to the deprecated startActivityForResult. You can also refer settings panel article where we are using the Activity Result API for launching the settings panel.