Android App

Google login in Android Studio

YunSeong 2021. 11. 8. 23:28
728x90
반응형

https://youtu.be/FrRo26dYGfc

 

 

1. Firebase에서 설정

https://console.firebase.google.com/

 

로그인 - Google 계정

하나의 계정으로 모든 Google 서비스를 Google 계정으로 로그인

accounts.google.com

위 링크에서 로그인하고 프로젝트를 만든 후 Authentication에 들어가서 로그인 제공업체로 google을 등록한다. 

또한 프로젝트에 안드로이드 앱 또한 등록한다. 

 

그 과정에서 설정이 나오는데로

app\Gradle Scripts\build.gradle (:app) (1)와

app\Gradle Scripts\build.gradle (<appName>) (2)에 아래와 같이 추가한다.

 

(1)

1
2
3
4
5
6
7
8
9
10
            ...
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
 
dependencies {
            ...
    implementation platform('com.google.firebase:firebase-bom:29.0.0')
 
    implementation 'com.google.firebase:firebase-analytics'
}
cs

(2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
buildscript {
    repositories {
        google()
         ...
    }
    dependencies {
                    ...
        classpath 'com.google.gms:google-services:4.3.10'
    }
}
 
allprojects {
    repositories {
        google()
                ...
    }
}
        ...
cs

2. 라이브러리

 1) app\Gradle Scripts\build.gradle (:app)

1
2
3
4
5
6
7
8
        ...
dependencies {
    implementation 'com.google.firebase:firebase-auth:19.1.0'//google 로그인 인증관련1
    implementation 'com.firebaseui:firebase-ui-auth:4.2.1'//google 로그인 인증관련2
    implementation 'com.github.bumptech.glide:glide:4.9.0'//글라이드 이미지 로딩 관련1
    annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'//글라이드 이미지 로딩 관련2
        ...
}
cs

위와 같이 google 로그인 인증에 필요한 라이브러리와 url로 사진을 로딩하기 위한 라이브러리를 등록한다.


2) app\Gradle Scripts\gradle.properties

1
android.enableJetifier=true
cs

위 줄을 코드에 추가해서 라이브러리가 제대로 작동하도록한다.


3. activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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.google.android.gms.common.SignInButton
        android:id="@+id/btn_google"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
</androidx.constraintlayout.widget.ConstraintLayout>
cs

11~18 - com.google.android.gms.common.SignInButton 태그를 이용해서 편하게 로그인용 버튼을 만들 수 있다.


4. activity_result.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
<?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:id="@+id/tv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ResultActivity"
    android:orientation="vertical">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_gravity="center"
        tools:srcCompat="@tools:sample/avatars" />
    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="닉네임"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:textSize="24sp" />
</LinearLayout>
cs

로그인 했을 때 띄울 Activity를 만들어준다. 

10~15, 16~23 - 로그인 됐을 때 그 계정의 닉네임프로필 사진을 띄울 위젯을 만든다.


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
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.example.googleloginexample;
 
import ...
 
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
 
    private SignInButton btn_google;
    private FirebaseAuth auth;
    private GoogleApiClient googleApiClient;
    private static final int RED_SIGN_GOOGLE = 100;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
 
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(thisthis)
                .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
                .build();
 
        auth = FirebaseAuth.getInstance();
 
        btn_google = findViewById(R.id.btn_google);
        btn_google.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); // 구글에서 제공하는 인증하는 intent
                startActivityForResult(intent, RED_SIGN_GOOGLE);
            }
        });
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        if (requestCode == RED_SIGN_GOOGLE){
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()){
                GoogleSignInAccount account = result.getSignInAccount();
                resultLogin(account); //로그인 이벤트
            }
        }
    }
 
    private void resultLogin(GoogleSignInAccount account) { //로그인 이벤트
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        auth.signInWithCredential(credential)
                .addOnCompleteListener(thisnew OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull @NotNull Task<AuthResult> task) {
                        if (task.isSuccessful()) { //로그인 성공했을 때 이벤트
                            Toast.makeText(MainActivity.this,"로그인 성공", Toast.LENGTH_SHORT);
                            Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
                            intent.putExtra("nickName", account.getDisplayName());
                            intent.putExtra("photoUrl"String.valueOf(account.getPhotoUrl()));
 
                            startActivity(intent);
                        } else { //로그인 했을 때 이벤트
                            Toast.makeText(MainActivity.this,"로그인 실패", Toast.LENGTH_SHORT);
                        }
                    }
                });
    }
 
    @Override
    public void onConnectionFailed(@NonNull @org.jetbrains.annotations.NotNull ConnectionResult connectionResult) {
 
    }
}
cs

46번 줄에서 초기화 된 GoogleSignInAccount account에 계정에 대한 정보들이 들어있어서 

61~62번 줄에서처럼 정보를 뽑아서 사용할 수 있다.


6.ResultActivity.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
package com.example.googleloginexample;
 
import ...
 
public class ResultActivity extends AppCompatActivity {
 
    private TextView textView;
    private ImageView imageView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
 
        textView = findViewById(R.id.textView2);
        imageView = findViewById(R.id.imageView);
        Intent intent = getIntent();
        String nickName = intent.getStringExtra("nickName");
        String photoUrl = intent.getStringExtra("photoUrl");
 
        textView.setText(nickName);
        Glide.with(this).load(photoUrl).into(imageView);
    }
}
cs

위와 같이 intent전 Activity에서 전달받은 정보를 가지고 이 Activity에서 띄워준다.

728x90
반응형