반응형
Notice
Recent Posts
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

500error

[안드로이드, Kotlin] 구글 로그인 구현 본문

안드로이드/코틀린

[안드로이드, Kotlin] 구글 로그인 구현

Internal Server Error 2024. 10. 15. 00:21
반응형
import android.app.Activity
import android.content.Intent
import android.util.Log
import android.widget.Toast
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException

class LoginGoogle(activity: Activity) {

    private var googleSignInClient: GoogleSignInClient

    init {
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build()

        googleSignInClient = GoogleSignIn.getClient(activity, gso)
    }

    fun signIn(activity: Activity) {
        val signInIntent = googleSignInClient.signInIntent
        activity.startActivityForResult(signInIntent, RC_GOOGLE_SIGN_IN)
    }


    fun handleSignInResult(data: Intent?, onGoogleSignInComplete: (GoogleSignInAccount?) -> Unit) {
        val task = GoogleSignIn.getSignedInAccountFromIntent(data)
        try {
            val account = task.getResult(ApiException::class.java)
            onGoogleSignInComplete(account)
        } catch (e: ApiException) {
            Log.e("LoginGoogle", "Google sign in failed", e)
        }
    }

//    fun signOut(activity : Activity) {
//        googleSignInClient.signOut()
//            .addOnCompleteListener {
//                Toast.makeText(activity, "로그아웃 되셨습니다!", Toast.LENGTH_SHORT).show()
//            }
//    }

    companion object {
        const val RC_GOOGLE_SIGN_IN = 9001
    }
}

 

LoginGoogleActivity



override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // Google 로그인 결과 처리
        if (requestCode == LoginGoogle.RC_GOOGLE_SIGN_IN) {
            googleSignIn.handleSignInResult(data) { account ->
                // Google 로그인 완료 후 처리할 내용
                if (account != null) {
                    // 로그인 성공
                    // account를 사용하여 필요한 작업 수행
                    onGoogleSignInComplete(account)
                } else {

                    cprgBar.dismiss()


                    Toast.makeText(
                        this,
                        "구글 로그인 실패",
                        Toast.LENGTH_SHORT)
                        .show()
                }
            }
        }
    }

 

 

LoginActivity

반응형
Comments