Android App

Kakao login in Android Studio

YunSeong 2021. 11. 12. 23:32
728x90
반응형

https://youtu.be/721kVMWKqP8

1. 카카오 연동

https://developers.kakao.com/docs/latest/ko/getting-started/sdk-android-v1#import

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

위 링크의 페이지의 설명대로 안드로이드 프로젝트에 라이브러리나 그에 관련된 것들을 작업해줘야한다.

그리고 "내 애플리케이션"에서 앱을 등록해주고 "키 해시"까지 등록해줘야한다.


2. 관련 라이브러리

1)  build.gradle (:app)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        ...
dependencies {
 
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
 
    implementation group: 'com.kakao.sdk', name: 'usermgmt', version: '1.30.6'
 
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
 
    implementation 'org.jetbrains:annotations:15.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
cs

위와 같이 url을 통해서 사진을 imageView 뛰우기 위한 라이브러리를 추가한다.


2) gradle.properties

1
android.enableJetifier=true
cs

위에서 추가한 github 라이브러리를 제대로 작동시키기 위해서 위와 같은 코드를 추가해준다.


3. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">
 
    <com.kakao.usermgmt.LoginButton
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs

9~15 - 위와 같은 "com.kakao.usermgmt.LoginButton"라는 tag를 이용해서 카카오 로그인 버튼을 만들 수 있다.


4. CustomApplication.java

카카오 로그인을 사용하기 위해서 위와 같은 자바 파일을 만들어야한다.

https://github.com/hongdroid94/46_KakaoLogin/blob/master/app/src/main/java/com/hongdroid/kakaologinexample/CustomApplication.java

 

GitHub - hongdroid94/46_KakaoLogin: 카카오 로그인 & 로그아웃

카카오 로그인 & 로그아웃. Contribute to hongdroid94/46_KakaoLogin development by creating an account on GitHub.

github.com

코드는 위 링크의 페이지에 있다.

그리고 위에서 만든 자바 파일을 AndroidManifest.xml 아래와 같이 추가해줘야한다.(8열)

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kakaologinexample">
 
    <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:name=".CustomApplication"
                ...
    </application>
 
</manifest>
cs

5. MainActivity.java

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.example.kakaologinexample;
 
import ...
 
public class MainActivity extends AppCompatActivity {
 
    private ISessionCallback mSessionCallback;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        mSessionCallback = new ISessionCallback() {
            @Override
            public void onSessionOpened() { // 로그인 요청
                UserManagement.getInstance().me(new MeV2ResponseCallback() {
                    @Override
                    public void onFailure(ErrorResult errorResult) { //로그인 실패
                        Toast.makeText(MainActivity.this"로그인에 실패하셨습니다. 다시 시도해주세요", Toast.LENGTH_SHORT).show();
 
                    }
 
                    @Override
                    public void onSessionClosed(ErrorResult errorResult) { //세션이 닫힘
                        Toast.makeText(MainActivity.this"세션이 닫혔습니다. 다시 시도해주세요", Toast.LENGTH_SHORT).show();
                    }
 
                    @Override
                    public void onSuccess(MeV2Response result) { //로그인 성공
                        Intent intent = new Intent(MainActivity.this, SubActivity.class);
                        intent.putExtra("Nickname", result.getKakaoAccount().getProfile().getNickname());
                        intent.putExtra("profileImg", result.getKakaoAccount().getProfile().getProfileImageUrl());
                        intent.putExtra("email", result.getKakaoAccount().getEmail());
                        startActivity(intent);
                        Toast.makeText(MainActivity.this"로그인에 성공하셨습니다.", Toast.LENGTH_SHORT).show();
 
                    }
                });
            }
 
            @Override
            public void onSessionOpenFailed(KakaoException exception) {
 
            }
        };
 
        Session.getCurrentSession().addCallback(mSessionCallback);
        Session.getCurrentSession().checkAndImplicitOpen();
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, data))
            super.onActivityResult(requestCode, resultCode, data);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Session.getCurrentSession().removeCallback(mSessionCallback);
    }
}
cs

14~46 - 위 열에서 로그인에 대한 이벤트를 설정할 수 있다.

    - 30열에서 parameter로 받은 result프로필에 대한 정보를 가지고 있다.

48~49 - 이 열에서 설정한 이벤트를 실제로 올린다.

52~62 - 이 열에서 다른 activity에서 이 activity로 돌아왔을때 제대로 작동하도록 한다.


6. activity_sub.xml

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".SubActivity">
 
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />
 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
 
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
 
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="로그아웃"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>
cs

위와 같이 로그인을 했을 때 띄울 SubActivity를 만든다.


7. SubActivity.java

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
32
33
34
35
package com.example.kakaologinexample;
 
import ...
 
public class SubActivity extends AppCompatActivity {
    private TextView textView1, textView2;
    private ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub);
 
        Intent intent = getIntent();
 
        textView2 = findViewById(R.id.textView2);
        textView1 = findViewById(R.id.textView);
        imageView = findViewById(R.id.imageView);
 
        textView1.setText(intent.getStringExtra("Nickname"));
        textView2.setText(intent.getStringExtra("email"));
 
 
        Glide.with(this).load(intent.getStringExtra("profileImg")).into(imageView);
 
        findViewById(R.id.button).setOnClickListener(v -> {
            UserManagement.getInstance().requestLogout(new LogoutResponseCallback() {
                @Override
                public void onCompleteLogout() { //로그아웃 성공
                    finish();
                }
            });
        });
    }
}
cs

위 코드는 위에서 정의한 activity의 xml의 java파일이다. (즉 로그인을 했을 때 띄워질 Activity이다.)

26~33 - 버튼을 눌렀을 때 로그아웃을 하도록 정의하는 코드이다.

    - 29~31 - 로그아웃이 성공했을 때 이벤트를 정의하는 곳이다.

728x90
반응형