官方文献:
1、前期准备:
https://developers.google.cn/identity/sign-in/android/legacy-start-integrating?hl=zh-cnhttps://developers.google.cn/identity/sign-in/android/legacy-start-integrating?hl=zh-cn
2、具体开发:
新版 Google Sign-In API | Authentication | Google for Developershttps://developers.google.cn/identity/sign-in/android/sign-in-identity?hl=zh-cn
3、操作参考:
https://juejin.cn/post/7383652378370736167https://juejin.cn/post/7383652378370736167
代码实现:
1、直接复制我写的工具类:GoogleLoginUtils
/*** @Date: 2024/11/11* @Author: xinghai.zhao* @role:Google登录工具类*/
object GoogleLoginUtils {var mGoogleIdToken: String = "xxxx"fun goLogin(activity: AppCompatActivity) {//使用gso指定的选项构建一个GoogleSignInClientval client = GoogleSignIn.getClient(activity, GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail() //指定您的应用程序请求电子邮件信息.requestId() //指定您的应用程序请求用户标识.requestIdToken(mGoogleIdToken) //指定请求用于身份验证用户的ID令牌.requestProfile() //指定您的应用程序请求用户的个人资料信息.build())activity.registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->if(activityResult.resultCode == RESULT_OK) {handleSignInResult(activity,GoogleSignIn.getSignedInAccountFromIntent(activityResult.data))}}.launch(client.signInIntent)}fun handleSignInResult(activity: Activity, completedTask: Task<GoogleSignInAccount>) {try {val account = completedTask.getResult(ApiException::class.java)val displayName = account?.displayNameval email = account?.emailval id = account?.idval idToken = account?.idTokenLogUtil.e("google-displayName:${displayName},googleEmail:${email},googleId:${id},googleIdToken:${idToken}")googleLoginSuccess(activity, id, email) //将获取数据传入} catch (e: ApiException) {when (e.statusCode) {7 -> {LogUtil.e("网络不给力,请再试一次")}12500 -> {LogUtil.e("当前设备不支持")}10 -> {LogUtil.e("环境配置步错误,请稍后再试")}}LogUtil.e("google-LoginFailed${e.statusCode}")}}private fun googleLoginSuccess(activity: Activity, id: String?, email: String?) {val date = hashMapOf<String, String>()if (id != null) {date["id"] = id}if (email != null) {date["email"] = email}HttpUtils.post(activity, HttpUtils.URL_Login, date,onResponse = {//todo 请求成功后 json解析}, onFailure = {//todo 请求失败后处理})}
}
2、在Activity的登录按钮点击事件中调用:
GoogleLoginUtils.goLogin(this)
类中的网络请求工具HttpUtils来这里复制:
Android 用80行代码 封装最简单网络请求 HttpUtils-CSDN博客文章浏览阅读213次,点赞11次,收藏5次。在小型项目中,实现最简单最高效的网络请求封装 轻量化,不借助除okhttp以外的三方框架 单个类实现,且可读性高,扩展性高 最少的代码行数,最简单的调用方式https://zhaoxinghai.blog.csdn.net/article/details/143712192
_______________________________________________________________________
如果您感觉文章有用的话,麻烦点个赞吧! 如果您发现文章有任何错误或建议,请评论区留言或者私信! 深海谢过各位的支持,一起加油!