【问题标题】:Not Getting result from rememberLauncherForActivityResult() in jetpack compose没有从 jetpack compose 中的 rememberLauncherForActivityResult() 获取结果
【发布时间】:2021-10-18 09:26:52
【问题描述】:

我正在打电话给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}")
        }

【问题讨论】:

    标签: android android-activity android-jetpack-compose


    【解决方案1】:

    如果有人遇到同样的问题,那么只需使用这个可组合的而不是 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*/)
    

    【讨论】:

    • 代码中的 realLauncher 变量在哪里?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多