[Android Kotlin] Google Login & registerForActivityResult
Prologue
이번에 TodoList 어플을 개발하기로 했는데 로그인 방식으로 우선 구글 로그인을 사용하기로 했습니다.
Google Login API
1. Firebase에 프로젝트 연결
일단 구글 로그인을 하기 위해선 Firebase와 프로젝트가 연결되어 있어야 합니다.
[Firebase] Android에 Firebase 연동하기
구글에 Firebase입력하시면 아래와 같은 창이 뜨게 됩니다. 이제 시작하기와 프로젝트 만들기를 순서대로 눌러주시면 됩니다. Firebase는 총 3단계로 이루어져 있습니다. 순서대로 차근차근 입력하
jgeun97.tistory.com
1-1. 프로젝트 연동은 했는데 SHA-1만 알고 싶다면 링크를 확인하세요
[Android] SHA-1 key 쉽게 확인하기
예전에는 Gradle을 클릭해서 signingReport를 눌렀을 때 SHA-1의 정보를 확인할 수 있었습니다. 하지만 왜인지는 모르겠지만 안나오더라구요! 이럴 땐 terminal을 켜서 gradlew signingReport를 입력해주시면 됩
jgeun97.tistory.com
1-2. app의 build.gradle에 다음과 같은 dependencies 들을 추가해주셔야 합니다.
dependencies {
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:30.2.0')
// Declare the dependency for the Firebase Authentication library
// When using the BoM, you don't specify versions in Firebase library dependencies
implementation 'com.google.firebase:firebase-auth'
// Also declare the dependency for the Google Play services library and specify its version
implementation 'com.google.android.gms:play-services-auth:20.2.0'
}
1-3. 제품 카테고리 -> 빌드 -> Authentication -> Sign-in method -> 새 제공업체 추가 -> Google -> 설정
2. xml에 구글 로그인 버튼 생성
구글 로그인 버튼의 경우 브랜드 가이드라인을 지켜야만 배포가 가능합니다.
로그인 브랜드 가이드라인 | Google ID 플랫폼 | Google Developers
로그인 브랜드 가이드라인 모바일 또는 웹 앱에서 기본적인 profile 또는 email 범위로 Google 로그인을 사용하고 다음의 표준 버튼을 통합하세요. 다운로드 파일에 Sketch, SVG, EPS 파일이 포함되어 있
developers.google.com
저희는 일단 간단하게 구글에서 제공하는 컴포넌트를 사용하겠습니다. layout에 SignInButton을 입력해주세요.
<com.google.android.gms.common.SignInButton
android:id="@+id/login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
3. 코드 구현하기
3-1. 다음과 같은 변수들을 onCreate 위에 선언해주세요.
private lateinit var auth: FirebaseAuth
private lateinit var mGoogleSignInClient: GoogleSignInClient
private lateinit var startGoogleLoginForResult : ActivityResultLauncher<Intent>
3-2. registerActivity에 Google 연결하기
private fun googleInit() {
val default_web_client_id = {Google에서 제공하는 default_web_client_id}; // Android id X
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(default_web_client_id)
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
startGoogleLoginForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == RESULT_OK) {
result.data?.let { data ->
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
}
}
// Google Login Success
} else {
Log.e(TAG, "Google Result Error ${result}")
}
}
}
gso 변수를 만들기 위해선 Google에서 제공하는 default_web_client_id 가 필요합니다.
Google 클라우드 플랫폼
로그인 Google 클라우드 플랫폼으로 이동
accounts.google.com
위의 링크로 들어가시면 Firebase에서 연동했던 프로젝트들이 나오게 될 거예요.
여기서 Web client에 해당하는 클라이언트 ID를 복사해서 default_web_client_id에 저장해주시면 됩니다.
3-3. GoogleSignIn 성공 시 FirebaseAuthWithGoogle 연동하기
// [START auth_with_google]
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
updateUI(null)
}
}
}
3-4. updateUI에서는 해당 Activity에서 원하는 UI 작업을 진행해주시면 됩니다.
private fun updateUI(user: FirebaseUser?) {
// FirebaseUser 데이터에 따른 UI 작업
}
3-5. Google Login에 대해 registerActivityResult가 완료되었다면 버튼 클릭 시 Google 로그인이 되도록 하겠습니다
// OnCreate 안에서
binding.loginBtn.setOnClickListener {
val signInIntent = mGoogleSignInClient.signInIntent
startGoogleLoginForResult.launch(signInIntent)
}
https://github.com/JGeun/Android_Study/tree/master/GoogleLoginApi
GitHub - JGeun/Android_Study: This repository is an Android Study Collections
This repository is an Android Study Collections. Contribute to JGeun/Android_Study development by creating an account on GitHub.
github.com