Android/Social_login

[Android] 카카오 로그인 구현(kotlin) -2 (구현)

찌김이 2019. 11. 4. 20:37
728x90
반응형

 

이전 포스팅에 이어 아래 코드만 더 추가하면 구현이 가능해진다.

 

 

구현

1. GlobalApplication 추가

import android.app.Application
import com.kakao.auth.KakaoSDK

class GlobalApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        instance = this
        KakaoSDK.init(KakaoSDKAdapter())
    }

    override fun onTerminate() {
        super.onTerminate()
        instance = null
    }

    fun getGlobalApplicationContext(): GlobalApplication {
        checkNotNull(instance) { "this application does not inherit com.kakao.GlobalApplication" }
        return instance!!
    }

    companion object {
        var instance: GlobalApplication? = null
    }
}

 

2. KakaoSDKAdapter 추가

import com.kakao.auth.*

class KakaoSDKAdapter : KakaoAdapter() {
    override fun getSessionConfig(): ISessionConfig {
        return object : ISessionConfig {
            override fun getAuthTypes(): Array<AuthType> {
                // Auth Type
                // KAKAO_TALK  : 카카오톡 로그인 타입
                // KAKAO_STORY : 카카오스토리 로그인 타입
                // KAKAO_ACCOUNT : 웹뷰 다이얼로그를 통한 계정연결 타입
                // KAKAO_TALK_EXCLUDE_NATIVE_LOGIN : 카카오톡 로그인 타입과 함께 
                //                                   계정생성을 위한 버튼을 함께 제공
                // KAKAO_LOGIN_ALL : 모든 로그인 방식을 제공
                return arrayOf(AuthType.KAKAO_LOGIN_ALL)
            }

            override fun isUsingWebviewTimer(): Boolean {
                return false
            }

            override fun getApprovalType(): ApprovalType? {
                return ApprovalType.INDIVIDUAL
            }

            override fun isSaveFormData(): Boolean {
                return true
            }

            override fun isSecureMode(): Boolean {
                return true
            }
        }
    }

    override fun getApplicationConfig(): IApplicationConfig {
        return IApplicationConfig {
            GlobalApplication.instance?.getGlobalApplicationContext()
        }
    }
}

 

3. SessionCallback 추가

import android.util.Log
import com.kakao.auth.ISessionCallback
import com.kakao.network.ErrorResult
import com.kakao.usermgmt.UserManagement
import com.kakao.usermgmt.callback.MeV2ResponseCallback
import com.kakao.usermgmt.response.MeV2Response
import com.kakao.util.exception.KakaoException

class SessionCallback : ISessionCallback {
    override fun onSessionOpenFailed(exception: KakaoException?) {
        Log.e("Log", "Session Call back :: onSessionOpenFailed: ${exception?.message}")
    }

    override fun onSessionOpened() {
        UserManagement.getInstance().me(object : MeV2ResponseCallback() {

            override fun onFailure(errorResult: ErrorResult?) {
                Log.i("Log", "Session Call back :: on failed ${errorResult?.errorMessage}")
            }

            override fun onSessionClosed(errorResult: ErrorResult?) {
                Log.i("Log", "Session Call back :: onSessionClosed ${errorResult?.errorMessage}")

            }

            override fun onSuccess(result: MeV2Response?) {
                Log.i("Log", "아이디 : ${result!!.id}")
                Log.i("Log", "이메일 : ${result.kakaoAccount.email}")
                Log.i("Log", "프로필 이미지 : ${result.profileImagePath}")

                checkNotNull(result) { "session response null" }
            }

        })
    }
}

 

4. MainActivity

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.kakao.auth.Session


class MainActivity : AppCompatActivity() {

    private var callback: SessionCallback = SessionCallback()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Session.getCurrentSession().addCallback(callback);

    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        Session.getCurrentSession().removeCallback(callback);
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, data)) {
            Log.i("Log", "session get current session")
            return
        }
        super.onActivityResult(requestCode, resultCode, data)
    }
}

 

5. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <com.kakao.usermgmt.LoginButton
        android:id="@+id/btn_kakao_login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp" />
    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>
</LinearLayout>

 

결과

로그인하면 아이디, 이메일, 프로필 이미지 값이 넘어온다.

 

로그아웃 , 앱 연결 해제

1. activity_main.xml 추가

<Button
        android:id="@+id/logout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="로그아웃"/>

    <Button
        android:id="@+id/link_out"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="연결해제"/>

 

2. MainActivity 추가 - // onCreate() 안에 추가해주시면 됩니다.

// 로그아웃
        logout.setOnClickListener {
            val builder = AlertDialog.Builder(this)
            builder.setMessage("로그아웃 하시겠습니까?")
            builder.setPositiveButton("확인") { dialogInterface, i ->
                UserManagement.getInstance().requestLogout(object : LogoutResponseCallback() {
                    override fun onCompleteLogout() {

                    }
                })
                dialogInterface.dismiss()
            }
            builder.setNegativeButton("취소") { dialogInterface, i ->
                dialogInterface.dismiss()
            }
            val dialog: AlertDialog = builder.create()
            dialog.show()

        }

        // 앱연결 해제
        link_out.setOnClickListener {
            val builder = AlertDialog.Builder(this)
            builder.setMessage("앱 연결을 해제하시겠습니까?")
            builder.setPositiveButton("확인"){ dialogInterface, i ->
                    UserManagement.getInstance().requestUnlink(object : UnLinkResponseCallback() {
                        override fun onFailure(errorResult: ErrorResult?) {
                            Log.i("Log",errorResult!!.toString())
                        }
                        override fun onSessionClosed(errorResult: ErrorResult) {
                        }
                        override fun onNotSignedUp() {
                        }
                        override fun onSuccess(userId: Long?) {
                            Log.i("Log",userId.toString())
                        }
                    })
                    dialogInterface.dismiss()
                }
            builder.setNegativeButton("취소") { dialogInterface, i ->
                    dialogInterface.dismiss()
                }
            val dialog: AlertDialog = builder.create()
            dialog.show()
        }

 

로그인, 로그아웃, 앱연결 해제까지 모두 구현해냈다.

응용해서 잘 사용하면 될 것 같다.

728x90
반응형

'Android > Social_login' 카테고리의 다른 글

[Android] 카카오 로그인 구현(Kotlin) - 1(준비)  (0) 2019.11.03