Development record of developer who study hard everyday.

레이블이 파이어베이스구글로그인인 게시물을 표시합니다. 모든 게시물 표시
레이블이 파이어베이스구글로그인인 게시물을 표시합니다. 모든 게시물 표시
, , , , ,

안드로이드 firebase 파이어베이스로 구글로그인 구현 예제

 firebase 파이어베이스로 구글로그인 구현 예제

안드로이드 개발 블로그

1. firebase에 프로젝트 등록하기

https://antwhale94.blogspot.com/2022/09/blog-post.html

어려운거 아니니까 위 링크를 참고해서 따라하자


2. firebase console에서 구글로그인 추가하기

안드로이드 구글로그인 추가

안드로이드 프로젝트에 들어가서 Authenticate에 들어간다.


firebase authenticate 설정

시작하기 클릭


파이어베이스 구글로그인 설정

우리는 구글로그인 연습하는거니까 구글 버튼을 클릭한다


firebase 구글로그인 설정

사용설정 누르고 저장버튼 클릭


3. 웹 클라이언트 ID 저장

구글로그인 web client ID

google cloud platform에 들어가서 웹 클라이언트 아이디를 복사해서 strings.xml 파일에 저장해둔다.

<resources>
<string name="app_name">테스트앱</string>
<string name="double_back_exit_message">한번 더 누르면 앱이 종료됩니다.</string>

<string name="google_client_id">344721498191-m2lllw29379su8g21lpgj8.apps.googleusercontent.com</string>
</resources>


4. dependency 추가

dependencies {
// Firebase
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:26.0.0')
implementation 'com.google.android.gms:play-services-auth:20.3.0'
implementation 'com.google.firebase:firebase-auth'

}

위 코드처럼 dependency를 추가해준다.


5. 로그인 코드 작성

private lateinit var googleAuth : FirebaseAuth
private fun tryGoogleLogin() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.google_client_id))
.requestEmail()
.requestId()
.requestProfile()
.build()
val mGoogleSignInClient = GoogleSignIn.getClient(this, gso)

googleAuth = FirebaseAuth.getInstance()

val googleLoginIntent = mGoogleSignInClient.signInIntent
googleLoginLauncher.launch(googleLoginIntent)
}

val googleLoginLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
val data = activityResult.data
val task = GoogleSignIn.getSignedInAccountFromIntent(data)

try {
val account = task.result
firebaseAuthWithGoogle(account)
} catch (e: Exception) {
e.printStackTrace()
}
}

private fun firebaseAuthWithGoogle(account : GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle: ${account.id}")

val credential = GoogleAuthProvider.getCredential(account.idToken, null)
googleAuth.signInWithCredential(credential)
.addOnCompleteListener { task ->
if(task.isSuccessful){
Log.d(TAG, "signInWithCredential:success");
val user = googleAuth.currentUser
val id = account.id
val phoneNumber = user?.phoneNumber ?: ""
val email = user?.email ?: ""

Log.d(TAG, "id $id, email $email, phone $phoneNumber ")

//성공한 유저의 정보로 나머지 작업하기
} else {
Log.w(TAG, "signInWithCredential:failure", task.exception);

//로그인 실패


}
}

}


Share:
Read More