Android Kotlin - 实施 Google 凭据管理器时出现问题

问题描述 投票:0回答:1
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_google_login)

    gooLog()  
}


@Composable
fun gooLog(){

    val credentialManager = CredentialManager.create(this)
    val coroutineScope = rememberCoroutineScope()

    val googleIdOption: GetGoogleIdOption = GetGoogleIdOption.Builder()
        .setFilterByAuthorizedAccounts(false)
        .setServerClientId("blajo")
        .build()

    val request: GetCredentialRequest = GetCredentialRequest.Builder()
        .addCredentialOption(googleIdOption)
        .build()

    coroutineScope.launch {
        try {
            val result = credentialManager.getCredential(
                request = request,
                context = this@GoogleLogin,
            )
            handleSignIn(result)
        } catch (e: GetCredentialException) { Log.d("pikaboo", "I love google")}
    }
}

我试图让登录过程在活动打开后立即开始。

这样我就会得到这些错误:

@Composable invocations can only happen from the context of a @Composable function

在:

gooLog()
里面
Oncreate

Calls to launch should happen inside a LaunchedEffect and not composition

lunch
coroutineScope.launch


当我删除

@Composable
时,这些错误就会消失,但我明白了

Functions which invoke @Composable functions must be marked with the @Composable annotation

fun gooLog()

@Composable invocations can only happen from the context of a @Composable function

rememberCoroutineScope()

请帮忙

android kotlin google-signin
1个回答
0
投票

您正在以不受支持的方式将 XML 布局与 Jetpack Compose 混合。 您必须决定使用

setContentView(R.layout.activity_google_login)
来使用 XML 布局
setContent { gooLog() }
来使用 Compose。

但是,第一种方法不提供可组合上下文,因此您无法使用

gooLog()
,另一方面,第二种方法期望您的布局在
@Composable
函数中定义,因此您无法膨胀
R.layout.activity_google_login 
进入视图。

虽然存在一个 Interoperability API 允许您组合这两种方法,但看起来您实际上根本不需要 Compose。查看问题凭据管理器 - 如何创建“SignInWithGoogle”凭据?了解如何在不使用 Compose 的情况下进行设置。

© www.soinside.com 2019 - 2024. All rights reserved.