Android Google登录并获取token(亲测有效)

背景:

Android 需要用到Google的登录授权,用去token给到服务器,服务器再通过token去获取用户信息,实现第三方登录。

我们通过登录之后的email来获取token,不需要server_clientId;如果用server_clientId还需要在google的控制台配置测试的账号,否则登录的时候会返回错误码10.

实现步骤:

1、 手机或者Pad连接可以访问google的网络

2、最外层的build.gradle增加依赖

复制代码
dependencies {
    classpath 'com.google.gms:google-services:4.3.15'
}

app下的build.gradle增加依赖

复制代码
implementation 'com.google.android.gms:play-services-auth:20.6.0'

3、初始化谷歌服务

val googleSignInOptions = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)

.requestEmail() .build()

//这里不要调用requestIdToken

mGoogleSignInClient = GoogleSignIn.getClient(activity, googleSignInOptions)

4、检查google 服务器是否可用,手机是否有环境

复制代码
val isGooglePlayServicesAvailable=
    GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(activity)

5、如果没有环境,返回,流程结束

复制代码
if (isGooglePlayServicesAvailable!= ConnectionResult.SUCCESS) {
    // 验证是否已在此设备上安装并启用Google Play服务,以及此设备上安装的旧版本是否为此客户端所需的版本
    GoogleApiAvailability.getInstance().makeGooglePlayServicesAvailable(activity)
    return@launchIO
}

6、如果有环境,调用google的登录,调转到第三方app

复制代码
val signInIntent: Intent = mGoogleSignInClient!!.signInIntent
activity.startActivityForResult(
    signInIntent,
    100
)

7、重写Activity的这个方法,然后获取token

复制代码
fun onActivityResult(requestCode: Int, data: Intent?) {
    if (requestCode == 100) {
复制代码
      val completedTask: Task<GoogleSignInAccount> =
    GoogleSignIn.getSignedInAccountFromIntent(data)
val account: GoogleSignInAccount =
    completedTask.getResult(ApiException::class.java)
val status: Task<GoogleSignInAccount> = completedTask
if (!status.isSuccessful) {
    throw Exception(status.exception)
}

Log.d("测试", "account.email: " + account.email)

var loginGoogleRequest = LoginGoogleRequest()
loginGoogleRequest.bizId = CoreConstant.bizId
// Obtain token for access gmail account
var token: String =
GoogleAuthUtil.getToken(
CoreVariable.coreApplication,
account.email!!,
"oauth2:profile email"
)
Log.d("测试", "token= " + token)
}

相关推荐
张小姐的猫3 小时前
【MySQL】访问 & 数据流动原理
android·数据库·mysql·adb·1024程序员节
朱涛的自习室6 小时前
212 个需求、22 万行代码:Agent 接管开源项目的 19 天
android·前端·人工智能
传奇开心果11 小时前
【Flutter踩坑排雷】第3课:const 误用坑|const 错误使用引发 UI 异常与性能损耗
android·flutter
哲鲤11 小时前
AOSP思绎|Android 多媒体:一段视频为什么需要这么多服务
android
阿杰m11 小时前
Android源码第三章:Handler、Looper 与 MessageQueue——一条消息如何入队、唤醒并执行
android
海雅达手持终端PDA14 小时前
巡线、深井、爆管抢修与极寒水网的硬件矩阵怎么配?海雅达水务巡检终端PDA选型指南
android·物联网·5g·集成测试·能源·政务
恋猫de小郭16 小时前
Flutter 开始支持 Jetpack Compose Platform View
android·前端·flutter
三少爷的鞋1 天前
Android 架构七条铁律:架构师真正设计的不是代码,而是秩序
android
xiangxiongfly9151 天前
Android GsonFactory总结
android·gson·gsonfactory
WythePlus1 天前
Android 14 SELinux策略深度解析
android·安全策略·selinux策略