반응형
GoogleTestActivity.kt
class GoogleTestActivity : AppCompatActivity() {
/**
* [Document]: https://firebase.google.com/docs/auth/android/google-signin?authuser=0#top_of_page
* [Blog]: https://sh-itstory.tistory.com/60
*/
val TAG = "FFF"
private lateinit var googleSignInClient: GoogleSignInClient //구글 API 클라이언트
private lateinit var auth: FirebaseAuth //파이어베이스 인증객체
private val RC_SIGN_IN = 100 //구글로그인 rusult 상수
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_google_test)
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
// Initialize Firebase Auth
auth = FirebaseAuth.getInstance()
initLayout()
}
private fun initLayout(){
//버튼 모양만 잡아줄 뿐 기능은 없음
btn_googleSignIn.setOnClickListener {
signIn()
}
btn_logout.setOnClickListener {
signOut()
}
btn_google.setOnClickListener {
signIn()
}
}
public override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
Log.d(TAG, "onStart()에서 로그인확인: $currentUser, ${currentUser?.displayName} ${currentUser?.email}")
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.id!!)
val credential = GoogleAuthProvider.getCredential(acct.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)
Toast.makeText(this, "Authentication Failed.", Toast.LENGTH_LONG).show()
updateUI(null)
}
}
}
private fun updateUI(user: FirebaseUser?){
Log.d(TAG, "updateUI( $user )")
}
private fun signOut(){
Log.d(TAG, "signOut()")
FirebaseAuth.getInstance().signOut()
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// ...
}
}
}
}
activity_google_test.kt
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GoogleTestActivity">
<com.google.android.gms.common.SignInButton
android:id="@+id/btn_googleSignIn"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent" app:layout_constraintBottom_toBottomOf="parent"
>
</com.google.android.gms.common.SignInButton>
<Button
android:text="로그아웃"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_logout" android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/btn_googleSignIn" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"/>
<Button
android:text="구글로그인"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn_google" android:layout_marginBottom="32dp"
app:layout_constraintBottom_toTopOf="@+id/btn_googleSignIn"
app:layout_constraintStart_toStartOf="@+id/btn_googleSignIn"
app:layout_constraintEnd_toEndOf="@+id/btn_googleSignIn"/>
</android.support.constraint.ConstraintLayout>
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
Build.gradle
implementation 'com.google.firebase:firebase-auth:16.2.1'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
이건 먼저 콘솔에 가서 세팅을 다 해놓고,
Tools > Firebase 을 이용하면 자동으로 해준다.
app폴더 안에 파일 넣는 것도 해줌.
반응형
'Android > Firebase' 카테고리의 다른 글
Firebase Firestore 버킷 생성 시 리전 위치 (0) | 2021.05.16 |
---|---|
Cloud Firestore Database 시작하기 (0) | 2019.06.17 |
Google Auth (0) | 2019.01.30 |
Android에 Firebase 파일 추가 (0) | 2019.01.08 |
[Firebase] Cloud Firestore OR과 LIKE구현하기 (0) | 2018.08.02 |