问题:
如何为 GoogleSignInOptions.Builder()
定义 Gmail API 范围?
总结:
我有一个用 Kotlin 编写的 Android 应用程序,我试图在其中集成对 Gmail API 的调用,但无法添加 GMAIL_READONLY
请求范围时的范围。
相关信息和我的尝试:
来自文档 here :
...to configure Google Sign-In to request users' ID and basic profile information, create a
GoogleSignInOptions
object with theDEFAULT_SIGN_IN
parameter. To request users' email addresses as well, create theGoogleSignInOptions
object with therequestEmail
option.If you need to request additional scopes to access Google APIs, specify them with
requestScopes
.
我的应用程序 gradle 文件中有从 Java Gmail Quickstart 中获取的 Google API 客户端和 Gmail 服务依赖项:
implementation 'com.google.api-client:google-api-client:1.23.0'
implementation 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
implementation 'com.google.apis:google-api-services-gmail:v1-rev83-1.23.0'
在相应的片段中我有一个 setOnClickListener{}
用于进行 API 调用的按钮。按照之前链接的“将 Google 登录集成到您的 Android 应用程序”页面上的步骤,我有以下代码片段:
view.findViewById<Button>(R.id.google_sign_in_button).setOnClickListener {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
}
但是,当我尝试添加 Gmail.READONLY 范围时遇到构建错误。
例子:
使用下面的声明
val gmailScope = Scope(GmailScopes.GMAIL_READONLY)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(GmailScopes.GMAIL_READONLY)
.build()
给出 Type mismatch
错误,所需类型为 Scope
和 GmailScopes.GMAIL_READONLY
是字符串类型。 Gmail Java Quickstart 使用字符串列表定义范围:
Collections.singletonList(GmailScopes.GMAIL_LABELS);
但是将其与
.requestScopes(Collections.singletonList(GmailScopes.GMAIL_LABELS))
给出相同类型的错误,自然是一个 Mutable List<String>
而不是之前的字符串。
Scope
Google APIs for Android 中记录的类页面将构造函数定义为:
Scope(String scopeUri)
: Creates a new scope with the given URI.
所以我尝试使用此类来实现:
val gmailScope = Scope(GmailScopes.GMAIL_READONLY)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestScopes(gmailScope)
.build()
也可以直接使用 URI:
val gmailScope = Scope("https://www.googleapis.com/auth/gmail.readonly")
然而,这给出了一个 Unresolved refernce: Scope
错误。我听从了 this question 的建议但无济于事。
最佳答案
回答:
.kt
文件缺少从 android.gms.common.api
导入的 Scope
类。
导入行:
import com.google.android.gms.common.api.Scope
关于android-studio - 将 GoogleSignInOptions.requestScopes() 用于 Gmail API 时如何定义范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61821881/