如何用 ActivityResultLauncher 替换 startActivityForResult 但仍然包含选项 Bundle?

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

startActivityForResult(intent: Intent!, options: Bundle?) 已弃用。我正在尝试用 ActivityResultLauncher 替换,但我需要通过 options。我怎样才能用新方法做到这一点?下面是原始(现已弃用)方法的示例,该方法将打开“联系人”菜单,然后根据 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
            }
        }
    }
}

我试图将上面的转换为使用 ActivityResultLauncher 但我还没有想出如何将 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
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
            }
        }
    }
}

在这种情况下,您需要创建两个单独的 ActivityResultLauncher 对象,每种情况一个。

IMO,这正是 Google 试图解决的问题,具有混乱的“onActivityResult”函数,并且必须处理 requestCodes。现在,这更类似于 OnClickListener 类型的回调。

他们对 Android 的其他部分做了同样的事情,比如请求应用权限。 requestCode 现在在内部处理。

'launch()' 的重载版本允许您在输入之外传递 'ActivityOptionsCompat'。

@看: https://developer.android.com/reference/androidx/activity/result/ActivityResultLauncher