android - 没有从 jetpack compose 中的 rememberLauncherForActivityResult() 获取结果
问题描述
我正在打电话StartIntentSenderForResult()
,但它没有被调用。
val authResult = rememberLauncherForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) {
Log.d("appDebug", "called!!!") // not get called
}
oneTapClient.beginSignIn(signUpRequest)
.addOnSuccessListener(activity) { result ->
try {
// Calling here for result
authResult.launch(
IntentSenderRequest
.Builder(result.pendingIntent.intentSender)
.build()
)
} catch (e: IntentSender.SendIntentException) {
Log.d("appDebug", "CATCH : ${e.localizedMessage}")
}
}
.addOnFailureListener(activity) { e ->
Log.d("appDebug", "FAILED : ${e.localizedMessage}")
}
解决方案
如果有人有同样的问题,那么只需使用这个可组合的而不是rememberLauncherForActivityResult()
.
感谢@Róbert Nagy 参考:https ://stackoverflow.com/a/65323208/15301088
我从原始帖子中删除了一些不推荐使用的代码,现在它对我来说很好。
@Composable
fun <I, O> registerForActivityResult(
contract: ActivityResultContract<I, O>,
onResult: (O) -> Unit
): ActivityResultLauncher<I> {
val owner = LocalContext.current as ActivityResultRegistryOwner
val activityResultRegistry = owner.activityResultRegistry
// Tracking current onResult listener
val currentOnResult = rememberUpdatedState(onResult)
// Only need to be unique and consistent across configuration changes.
val key = remember { UUID.randomUUID().toString() }
DisposableEffect(activityResultRegistry, key, contract) {
onDispose {
realLauncher.unregister()
}
}
return realLauncher
}
例如
val registerActivityResult = registerForActivityResult(
contract = ActivityResultContracts.StartIntentSenderForResult()
) {
// handle your response
}
// just call launch and pass the contract
registerActivityResult.launch(/*Your Contract*/)
推荐阅读
- python - 在 macOS BigSur 上使用 Python 3.9.1 安装 Numpy 1.19.5 时出现问题
- windows - 有没有办法在启动 Windows 10 Powershell 时自动运行初始化脚本?
- java - DateTimeFormatter 返回错误的年份
- maven - 如何让 Maven 查看 JOOQ 生成的其他 Kotlin 源文件夹?
- objective-c - 无法构建 Objective-C 模块“ChameleonFramework”
- ethereum - web3.js中结构映射的访问映射
- reactjs - React mapbox gl draw如何更改控件中的值
- c# - " CS0122 ' 集合
.Items' 由于其保护级别而无法访问“但对象是公共的 - excel - Excel - 布尔值的总和/计数
- python - 2个大熊猫数据集的条件合并