Search code examples
androidonactivityresult

How to replace startActivityForResult with ActivityResultLauncher but still include options Bundle?


startActivityForResult(intent: Intent!, options: Bundle?) has been deprecated. I am trying to replace with ActivityResultLauncher but I need to pass the options. How can I do this with the new method? Below is an example of the original (now deprecated) method that would open the Contacts menu and then do one of two things in the switch based on the value of code:

...
val code = contactType //can be either 1 or 2
val contactsIntent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
contactsIntent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
startActivityForResult(contactsIntent, code)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if(resultCode == Activity.RESULT_OK) {
        when(requestCode) {
            1 -> { //Do something
            }
            2 -> { //Do something else
            }
        }
    }
}

I have tried to convert the above to use ActivityResultLauncher but I haven't figured out how to pass the value of code to it. Below is what I have so far:

val code = contactType //can be either 1 or 2
val contactsIntent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
contactsIntent.type = ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE
contactLauncher.launch(contactsIntent) //or maybe contactLauncher.launch(contactsIntent, code)?

private val contactLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
    if(it.resultCode == Activity.RESULT_OK) {
        when(??? requestCode ???) {
            1 -> { //Do something
            }
            2 -> { //Do something else
            }
        }
    }
}

Solution

  • In this situation, you'll need to create two separate ActivityResultLauncher objects, one for each case.

    IMO, this is exactly what Google was trying to solve, having a cluttered "onActivityResult" function, as well as having to deal with requestCodes. Right now, this is more similar to an OnClickListener kind of callback.

    They did the same with other parts of Android, like requesting app permissions. The requestCode is now handled internally.