# Firebase with Android Studio part-4 : Using Google accunt sign-in Firebase ## 開始吧 ### 前置作業 * 參考[Part-1](https://hackmd.io/OVJ6GLpPR_Kb5kA-85kdgQ?view) ### gradle * 增加一個play-services:auth ```kotlin= implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.1.1' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.3' implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.3' implementation 'com.google.android.gms:play-services-auth:19.0.0' ``` ### UI * 這裡只使用一顆按鈕.. ### 找到你的auth client id * 把目錄切換到Project,並在app底下找到google-services.json並打開  * 我們會使用到client_id  * 並將ID加入資源檔,可以放在strings.xml也可以放在local.properties ### 設定Firebase * 在專案設定加入SHA-A  * 登入方式打開Google  ### 撰寫登入功能 * 宣告GoogleSignInOptions並帶入我們的webClient_id * 並用Intent方式啟動google登入頁面 * OnActivityResult已經停用了,改用registerForActivityResult * 注意到程式碼第12行,ActivityResultLauncher必須在生命週期onStarted之前,相當於在onCreate就要註冊,但是這個例子有按鈕的點擊監聽,所以當執行app時候,是在發生click事件才進行註冊,所以app會噴掉,以至於這個例子要把它移出click listener。 ```kotlin= class MainActivity : AppCompatActivity() { private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) auth = FirebaseAuth.getInstance() val registerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { ActivityResult -> if (ActivityResult.resultCode == Activity.RESULT_OK) { getIntentData(ActivityResult.data) } } findViewById<Button>(R.id.button).setOnClickListener { val options = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(BuildConfig.webclinet_id) .requestEmail() .build() val signInClient = GoogleSignIn.getClient(this, options) registerLauncher.launch(signInClient.signInIntent) } } private fun getIntentData(data: Intent?) { GoogleSignIn.getSignedInAccountFromIntent(data).result?.let { googleAuthForFirebase(it) } } private fun googleAuthForFirebase(account: GoogleSignInAccount) { val credentials = GoogleAuthProvider.getCredential(account.idToken, null) CoroutineScope(Dispatchers.IO).launch { try { auth.signInWithCredential(credentials).await() withContext(Dispatchers.Main) { Toast.makeText(this@MainActivity, "登入成功", Toast.LENGTH_LONG).show() } } catch (e: Exception) { withContext(Dispatchers.Main) { Toast.makeText(this@MainActivity, e.message, Toast.LENGTH_LONG).show() } } } } } ``` 參考資料 [Philipp Lackner's channel](https://www.youtube.com/watch?v=mhLlbWQ0p4s) ###### tags: `Firebase` `kotlin` `Android`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up