68 lines
2.4 KiB
Kotlin
68 lines
2.4 KiB
Kotlin
package com.example.module_google.login
|
|
|
|
import android.app.Activity
|
|
import android.content.Intent
|
|
import com.example.module_base.support.login.ILoginService
|
|
import com.example.module_base.support.login.LoginSDKException
|
|
import com.example.module_base.support.login.PlatformInfo
|
|
import com.example.module_google.BuildConfig
|
|
import com.google.android.gms.auth.api.signin.GoogleSignIn
|
|
import com.google.android.gms.auth.api.signin.GoogleSignInClient
|
|
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
|
|
import com.google.android.gms.common.api.ApiException
|
|
import kotlin.random.Random
|
|
|
|
/**
|
|
* Created by Max on 2023/11/22 15:59
|
|
* Desc:Google登录
|
|
**/
|
|
class GoogleLoginService : ILoginService {
|
|
private val requestCode = Random.nextInt(10000, 20000)
|
|
|
|
private var listener: ILoginService.Listener? = null
|
|
|
|
private var googleSignInOptions: GoogleSignInOptions =
|
|
GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
|
|
.requestEmail()
|
|
.requestProfile()
|
|
.requestIdToken(BuildConfig.GOOGLE_SERVER_CLIENT_ID)
|
|
.build()
|
|
|
|
private var googleSignInClient: GoogleSignInClient? = null
|
|
|
|
override fun login(activity: Activity, listener: ILoginService.Listener) {
|
|
this.listener = listener
|
|
if (this.googleSignInClient == null) {
|
|
this.googleSignInClient =
|
|
GoogleSignIn.getClient(activity.applicationContext, googleSignInOptions)
|
|
}
|
|
activity.startActivityForResult(
|
|
googleSignInClient!!.signInIntent,
|
|
requestCode
|
|
)
|
|
}
|
|
|
|
override fun logout() {
|
|
googleSignInClient?.signOut()
|
|
}
|
|
|
|
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
|
if (requestCode == this.requestCode) {
|
|
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
|
|
try {
|
|
val account = task.getResult(ApiException::class.java)
|
|
val info = PlatformInfo(
|
|
id = account!!.id!!,
|
|
name = account.displayName,
|
|
gender = null,
|
|
avatar = account.photoUrl?.toString()
|
|
)
|
|
listener?.onSuccess(info)
|
|
} catch (e: ApiException) {
|
|
listener?.onFailure(LoginSDKException(e.statusCode, e))
|
|
} catch (e: Exception) {
|
|
listener?.onFailure(LoginSDKException(-100))
|
|
}
|
|
}
|
|
}
|
|
} |