Android Firebase Google帳號登入
- 文章目錄
1.導入Firebase專案
https://badgameshow.com/fly/firebase-authentication/fly/firebase/
2.新增SHA-1到Firebase
專案設定>SHA 憑證指紋>新增指紋
取得指紋sigingReport
3.導入Google Login
implementation 'com.google.android.gms:play-services-auth:19.0.0'
4.Google Login
private val GOOGLE_SIGN_IN_REQUEST = 40
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
val client = GoogleSignIn.getClient(requireContext(), gso)
startActivityForResult(client.signInIntent, GOOGLE_SIGN_IN_REQUEST)
5.Google Login Callback(信箱,大頭照,名稱)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == GOOGLE_SIGN_IN_REQUEST && resultCode == RESULT_OK) {
//獲取帳戶
val account = GoogleSignIn.getSignedInAccountFromIntent(data).getResult(ApiException::class.java)
//信箱
val email = account.email
//名稱
val displayName = acccount.displayName
//大頭照
val photoUrl = account.photoUrl
val credential = GoogleAuthProvider.getCredential(account?.idToken, null)
//將資料送給Firebase紀錄
FirebaseAuth.getInstance()
.signInWithCredential(credential)
}
}
6.登出Google帳號
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
val client = GoogleSignIn.getClient(requireContext(), gso)
client.signOut()
7.取得上次登入的Google帳號
GoogleSignIn.getLastSignedInAccount(this)