首页 > 解决方案 > 没有从 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}")
        }

标签: androidandroid-activityandroid-jetpack-compose

解决方案


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

推荐阅读