Android
[Android] 카카오톡 로그인 연동 / 카카오톡API사용 (ver.1.14.0) / 해시키구하기(Hashkey)
홍주인
2018. 11. 13. 12:22
일단 카카오톡 디벨로퍼를 가입해야해요!!
https://developers.kakao.com/
솔직히 말씀드리면, 카카오톡 디벨로퍼에 대부분 다 나와있긴한데, 안나와있는부분도 있고, 어느파일에 어느코드를 넣어야하는지 정확히 나와있지 않기때문에, 안드로이드를 많이 다뤄보지 않으신분들은 하기가 어렵습니다,,,ㅠㅠ
딱 안드로이드 카카오톡 로그인버튼 구현하는거까기 올려드릴게요!!!
그래서 저는 코드를 통째로 다 올려드리려구요!!
안드로이드 스튜디오에 왼쪽상단에서 찾아서 들어가실수 있고,
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.cookandroid.패키지이름"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".GlobalApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.kakao.sdk.AppKey" android:value="@string/kakao_app_key" /> <activity android:name="com.kakao.auth.authorization.authcode.KakaoWebViewActivity" android:launchMode="singleTop" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest>
|
자바파일 하나를 더 만들어주셔야해요. 추가하시는법은
GlobalApplication.java
package com.cookandroid.패키지이름; import android.app.Application; import android.content.Context;
import com.kakao.auth.ApprovalType; import com.kakao.auth.AuthType; import com.kakao.auth.IApplicationConfig; import com.kakao.auth.ISessionConfig; import com.kakao.auth.KakaoAdapter; public class GlobalApplication extends Application { private static GlobalApplication instance; public static final GlobalApplication getGlobalApplicationContext() { if (instance == null) throw new IllegalStateException("this application does not inherit com.kakao.GlobalApplication"); return instance; } protected static class KakaoSDKAdapter extends KakaoAdapter { /** * Session Config에 대해서는 default값들이 존재한다. * 필요한 상황에서만 override해서 사용하면 됨. * * @return Session의 설정값. */ @Override public ISessionConfig getSessionConfig() { return new ISessionConfig() { @Override public AuthType[] getAuthTypes() { return new AuthType[]{AuthType.KAKAO_LOGIN_ALL}; } @Override public boolean isUsingWebviewTimer() { return false; } @Override public boolean isSecureMode() { return false; } @Override public ApprovalType getApprovalType() { return ApprovalType.INDIVIDUAL; } @Override public boolean isSaveFormData() { return true; } }; } @Override public IApplicationConfig getApplicationConfig() { return new IApplicationConfig() { @Override public Context getApplicationContext() { return GlobalApplication.getGlobalApplicationContext(); } }; } } @Override public void onCreate() { super.onCreate(); instance = this; } }
|
MainActivity.java
package com.cookandroid.패키지이름; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.app.Activity; import android.content.Intent;
import com.kakao.auth.ISessionCallback; import com.kakao.auth.KakaoSDK; import com.kakao.auth.Session; import com.kakao.util.exception.KakaoException; import com.kakao.util.helper.log.Logger; public class MainActivity extends Activity { private SessionCallback callback; /** * 로그인 버튼을 클릭 했을시 access token을 요청하도록 설정한다. * * @param savedInstanceState 기존 session 정보가 저장된 객체 */ @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); KakaoSDK.init(new GlobalApplication.KakaoSDKAdapter());
callback = new SessionCallback(); Session.getCurrentSession().addCallback(callback); Session.getCurrentSession().checkAndImplicitOpen(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (Session.getCurrentSession().handleActivityResult(requestCode, resultCode, data)) { return; } super.onActivityResult(requestCode, resultCode, data); } @Override protected void onDestroy() { super.onDestroy(); Session.getCurrentSession().removeCallback(callback); } private class SessionCallback implements ISessionCallback { @Override public void onSessionOpened() { redirectSignupActivity(); } @Override public void onSessionOpenFailed(KakaoException exception) { if (exception != null) { Logger.e(exception); } } } protected void redirectSignupActivity() { final Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } }
|
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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:id="@+id/com_kakao_login" android:layout_width="300dp" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="350dp" android:layout_weight="1" />
</FrameLayout> |
res/values에 있는
strings.xml
<resources> <string name="app_name">패키지이름</string> <string name="kakao_app_key">자신의 카카오 네이티브앱키</string>
</resources> |
Gradle Scripts에 있는
build.gradle(Project: 패키지이름)
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript {
repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.1.4'
// NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } }
allprojects { repositories { google() jcenter() //kakao mavenCentral() maven { url 'http://devrepo.kakao.com:8088/nexus/content/groups/public/' } } }
task clean(type: Delete) { delete rootProject.buildDir }
|
build.gradle(Module:app)
apply plugin: 'com.android.application' android { compileSdkVersion 27 defaultConfig { applicationId "com.cookandroid.hakseek2" minSdkVersion 16 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:27.1.1' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' // 카카오 로그인 sdk를 사용하기 위해 필요. api group: 'com.kakao.sdk', name: 'usermgmt', version: '1.14.0' }
|
딱 이렇게 하시면, 안드로이드 코드는 끝납니다. 수정해야할 부분은
1. 패키지이름 바꿔줘야 하구요!!
2. 네이티브앱키 등록해주셔야하구요!! ( 카카오톡디벨로퍼가입 -> 앱생성하시면 나옵니다)
3. 해시키 구하는 코드(아무 프로젝트나 만들어서 실행하면됌. 모든 프로젝트 동일) / Logcat에서 keyhash검색해서 찾으시면 됩니다
MainActivity.java
package com.cookandroid.exam; import android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.util.Base64; import android.util.Log;
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getHashKey(); } private void getHashKey(){ PackageInfo packageInfo = null; try { packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } if (packageInfo == null) Log.e("KeyHash", "KeyHash:null");
for (Signature signature : packageInfo.signatures) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT)); } catch (NoSuchAlgorithmException e) { Log.e("KeyHash", "Unable to get MessageDigest. signature=" + signature, e); } } } }
|
안드로이드 스튜디오 아래쪽에 TODO / Logcat / Terminal / Build란에서 해시키를 보고서 카카오디벨로퍼 - 내계정 - 샘플앱 설정에 등록했습니다!!)
저는 학교 팀플을하는데, 제가 구현을 한다하고, 복붙만 하면 될줄알았는데.... 생각보다 오래걸렸네요..ㅠㅠㅠ