如何用活动结果 API 替换 startActivityForResult? [英] How to replace startActivityForResult with Activity Result APIs?
问题描述
我有一个主要活动,它根据条件作为调用不同活动的入口点.其中,我使用 Firebase Auth 来管理用户登录:
I have a main activity which serves as an entry point to call different activities, depending on condition. Among others, I use Firebase Auth to manage user sign in:
startActivityForResult(
AuthUI.getInstance().createSignInIntentBuilder()
.setAvailableProviders(providers)
.build(),
RC_SIGN_IN)
我覆盖了onActivityResult()
来区分返回的intent/data,例如:
I overwrite onActivityResult()
to distinguish the returned intent/data, for example:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_CODE_1 -> {
// update UI and stuff
}
RC_SIGN_IN -> {
// check Firebase log in
}
// ...
}
}
使用 文档 强烈推荐的 Activity Result API,我知道我应该在 ActivityResultLauncher
之前制作 prepareCall()
并确保启动时活动处于创建状态,但我仍然不明白如何处理多个活动像 onActivityResult()
一样优雅地(至少在一个地方)结果.
With the Activity Result APIs which is strongly recommended by the documentation, I get that I should make prepareCall()
before ActivityResultLauncher
and to make sure the activity is in created state when I launch, but I still don't understand how to handle multiple activity results gracefully (at least, in one place) like in onActivityResult()
.
看这篇文章,看来我需要实现多个 ActivityResultContract
类型的子内部类(因此有多个prepareCall()
?),因为它们被假设为不同的合同,我说得对吗?有人可以向我展示一些反映上述 onActivityResult()
逻辑的骨架示例吗?
Looking at this article, it seems I need to implement multiple child inner classes of ActivityResultContract
type (therefore multiple prepareCall()
's?), because they are suppose to be different contracts, am I correct? Can someone please show me some skeleton example that mirrors the above onActivityResult()
logic?
推荐答案
您可以根据需要调用任意数量的活动以获得结果,并为每个活动提供单独的回调:
You can call as many Activities for result as you wish and have separate callback for each:
val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult())
{ result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
// you will get result here in result.data
}
}
}
startForResult.launch(Intent(activity, CameraCaptureActivity::class.java))
您只需要指定 Activity 类 - CameraCaptureActivity::class.java
You just need to specify Activity class - CameraCaptureActivity::class.java
更新:
prepareCall() 方法已在 Activity 1.2.0-alpha04 和 Fragment 1.3.0-alpha04 中重命名为 registerForActivityResult().最后一行应该是 startForResult.launch(...)
感谢Rafael Tavares 更新
这篇关于如何用活动结果 API 替换 startActivityForResult?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!