본문 바로가기

Android

[Android] 구글 로그인 연동 코드/ Firebase

일단 시작하려하면, 안드로이드 프로젝트를 만들고. Firebase에서 프로젝트를 추가해야합니다


Android패키지이름은 안드로이드 프로젝트에 아래부분을 복사해서 붙여넣어주세요!!

이후에 구성파일 다운로드는 그대로 따라하시면됩니다!!

만약에 왼쪽에 파일들이 나와있는 구조가 달라서 찾지 못하시겠다면, 위에 있는 사진처럼, 안드로이드 누르셔서 프로젝트 누르시면 됩니다


Firebase SDK추가는 그대로 따라하시면 되지만, 버전이 다르기때문에 약간 바꿔주셔야합니다. 아래에 코드 그대로 올리겠습니다


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'
classpath 'com.google.gms:google-services:4.0.2'

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}


build.gradle(Module:app)

 apply plugin: 'com.android.application'


android {
compileSdkVersion 27
defaultConfig {
applicationId "com.cookandroid.googleloginexam"
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'
implementation 'com.google.firebase:firebase-core:16.0.5'
implementation 'com.firebaseui:firebase-ui-auth:4.2.1'
}
apply plugin: 'com.google.gms.google-services'


AndroidManifest.xml - 패키지아래에 4번째줄만 추가되었습니다.

 <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cookandroid.googleloginexam">
<uses-permission android:name="android.permission.INTERNET" />
<application
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>
</application>
</manifest>

마지막으로 앱을 실행시켜서 설치확인 해주시면 됩니다!!


후에 개발 - Authentication에서 로그인제공업체 - Google을 사용설정으로 바꿔주시구요!!


이제 나머지 java코드와 xml코드만 붙여넣어주시면 됩니다


MainActivity.java

 package com.cookandroid.googleloginexam;


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GoogleAuthProvider;

public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
SignInButton Google_Login;
private static final int RC_SIGN_IN = 100;
private FirebaseAuth mAuth;
private GoogleApiClient mGoogleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API,gso)
.build();
mAuth = FirebaseAuth.getInstance();
Google_Login = findViewById(R.id.Google_Login);
Google_Login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent,RC_SIGN_IN);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
}
else{
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(MainActivity.this, "인증 실패", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "구글 로그인 인증 성공", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}


activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>

<android.support.constraint.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.google.android.gms.common.SignInButton
android:id="@+id/Google_Login"
android:layout_width="310dp"
android:layout_height="50dp"
android:layout_marginBottom="15dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"></com.google.android.gms.common.SignInButton>
</android.support.constraint.ConstraintLayout>


후에 실행하시면 구글 로그인연동이 끝이납니다!!



혹시 R심볼이 빨간색으로 나온다면, build.gradle(Module:app)쪽에 코드를 확인해주세요. 혹시라도 다른게 있는지..


.enableAutoManage(this, this)이 부분에서 this가 빨간줄이 그어진다면, public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener 부분을 확인해주세요.


이상 구글로그인연동을 마치겠습니다