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 小时前
离线小游戏做“每日挑战”:日期当随机种子,整局存成 JSON,再加一个“我不是机器人”
android·kotlin·游戏开发
一铭111994 小时前
海豹办公 1.9.15 跨端办公软件实践 文档兼容 Access 数据库与移动 WebView 排错
android·数据库·electron·开源软件·access
geats人山人海5 小时前
java 7异常
android·java·开发语言
2601_962071006 小时前
Kimi K3 vs DeepSeek V4-Pro实测对比:2026年同一入口十道题,耗时与token消耗差在哪
android·java·数据库
右手吉他7 小时前
高通平台IA APN问题分析之二
android·物联网
夜雪一千7 小时前
MySQL 自增 ID 的底层原理与坑点
android·mysql·adb
不浪费一个字节8 小时前
一个纯 Python 实现的 APK 解析与设备操控工具箱
android
itmigrate8 小时前
PHP 导出大 CSV 时内存溢出的一次排查
android·开发语言·php
hai_android8 小时前
LiveEventBusCore 跨 Activity 通讯源码解析
android·kotlin·android jetpack
维克兜率天8 小时前
【维克】统计套利建模:从因子到信号的完整流程
android·开发语言·python·算法·kotlin