한국어
  • 전자상거래
    • IDC KR LA NY CA UK
    • 인터넷전화사업솔루션
    • 전자상거래 결재 지불 수단
    • PayPal 페이팔 전자상거래
    • Billing Softswitch 렌트
    • 무료국제전화 솔루션
    • Voipswitch Switch Billing
  • 번호 가입
    • 미국 카나다 로컬 번호
    • 한국 070번호
    • 50개국가 전화번호 개통
    • 050 안심번호 평생번호 팩스번호
    • 해외 유심 스마트폰 전화 데이타
    • 스마트폰 사양 기종별
    • 스마트폰 내부구조 기종별
  • 스마트폰 요금제
    • ◆국내유선무선
    • ◆프리미엄
    • ◆스탠다드
    • 곰신통화 군인통화 군인요금
    • 스마트폰 요금 최저가 정보
  • IPPBX/GW
    • 개인홈오피스용
    • 기업용 사업용
    • 선불카드사업용
    • Asterisk
    • 070 인터넷전화
  • Coding
    • Android
    • IPHONE
    • Linux
    • windows
    • WebProgram
    • DBProgramming
    • Node.js
    • https rest api
  • 스마트폰앱
    • 전화 다이얼러
    • 모바일 VOIP
    • 안드로이드 프로그램
    • 아이폰 앱 프로그램
    • 네트워크 프로그램
    • JAVA 자바
    • UI DESIGN
    • android JNI
    • http post get
    • 휴대폰 해외로밍
  • 소프트스위치
    • 상업용SW
    • opensips
    • kamailio
    • IPPBX솔루션
    • SIP LIB STACK
    • 회의통화
    • WEBRTC
    • IMS
    • smpp SMS MMS SERVER
  • 네트워킹
    • Network
    • Linux
    • Database
    • 통신기술
    • 단축키
    • 윈도우 서버
    • 기업용 VPN PPTP SSL MPLS
    • 데이타센터 datacenter Vmware
    • 엑셀 엑셀VBA
  • 통신법률
    • 국내외통신회사
    • 통신사 규정 법률
    • 통신서비스보안문제
    • 통신요금 유선 무선 데이타
  • 연락처
    • 연락처 Jssoslution
    • Server 네트워크
    • 교통 지하철 버스 노선
    • 검색엔진 등록 최적화
  • 지역정보
    • 중국 정보
    • 일본
    • 미국 카나다
    • 동남아시아
    • 유럽
    • 아프리카
    • 남미
    • 영국
    • 카나다
    • 인도 인디아
    • 태국
    • 베트남 정보

  • 회원 가입
  • 아이디/비밀번호 찾기
  • 인증 메일 재발송

스마트폰앱

  • 전화 다이얼러
  • 모바일 VOIP
  • 안드로이드 프로그램
  • 아이폰 앱 프로그램
  • 네트워크 프로그램
  • JAVA 자바
  • UI DESIGN
  • android JNI
  • http post get
  • 휴대폰 해외로밍
온누리070 플레이스토어 다운로드
    acrobits softphone
     온누리 070 카카오 프러스 친구추가온누리 070 카카오 프러스 친구추가친추
     카카오톡 채팅 상담 카카오톡 채팅 상담카톡
    
    
라인상담
    
라인으로 공유

    
공유하기
페북공유

   ◎위챗 : speedseoul


  
     PAYPAL
     
     PRICE
     

pixel.gif

    before pay call 0088 from app


글 수 58
  • 회원 가입
  • 로그인
  • Skin Info
  • Tag list
  • List
  • Webzine
  • Gallery

Android: Login with Google Account

admin
http://www.webs.co.kr/index.php?document_srl=3315414
2018.05.07 17:02:41 (*.160.88.18)
12377

http://www.androiddeft.com/2018/01/28/android-login-with-google-account/

In on of my previous article, I have explained how to implement login with Facebook. In this tutorial, we will see how can we authenticate the user with Google.

Table of Contents [hide]

  • 1 Creating a new Project
  • 2 Enabling Firebase Authentication
  • 3 Handling Login
  • 4 Demonstration
  • 5 Source Code and APK Files

Creating a new Project

1. Create a new Project in Android Studio with the name Sign in with Google.

Enabling Firebase Authentication

To authenticate with Google, you need to connect to Firebase first:

2. Open Tools => Firebase in Android Studio.

3. Now click on Authentication:

Sign in with Google - Connect to Firebase

4. Now Click on Email and Password Authentication.

5. From the window that appears, click on Connect to Firebase.

Sign in with Google - Connect to Firebase 2

6. From the popup window, country and click on Connect to Firebase:

Sign in with Google - Connect to Firebase 3

7. Now click on Add Firebase Authentication to your app. It will prompt you to accept the changes. This will add Firebase and Google API dependency to the project as shown below:

Sign in with Google - Connect to Firebase 4

8. In addition to the permissions added above, you need to add Google Play services Auth and Glide dependency. Glide is used for displaying profile picture after login.

build.gradle (Module: app)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.google.firebase:firebase-auth:11.8.0'
    implementation 'com.google.android.gms:play-services-auth:11.8.0'
    // Glide image library
    implementation 'com.github.bumptech.glide:glide:4.3.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
 
 
apply plugin: 'com.google.gms.google-services'

10. Now open Firebase Console, go to Authentication and click on Set up Sign-In method

Enable Google Sign In in the Firebase console 1

11. Now click on Google from the list of sign-in providers and Enable it.

Enable Google Sign In in the Firebase console 2

12. Also, you can edit the public facing name by going to Settings:

Enable Google Sign Change Public Facing name

13. Next, Open Google Identity Toolkit API and enable the API
Enabling Identity Toolkit API

Handling Login

14. In Android Studio, open activity_main.xml add a Login button, a Logout button, an Image View to display the Profile picture and a TextView to display the name.

activity_main.xml
XHTML
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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.androiddeft.signinwithgoogle.MainActivity">
 
    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:visibility="visible" />
 
    <ImageView
        android:id="@+id/profilePic"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:visibility="gone" />
 
    <TextView
        android:id="@+id/displayName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:visibility="gone" />
 
    <Button
        android:id="@+id/sign_out_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Logout"
        android:visibility="gone" />
 
</LinearLayout>

15. Update the MainActivity with the following code:

MainActivity.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package com.androiddeft.signinwithgoogle;
 
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.ApiException;
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.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
 
public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private static final int RC_SIGN_IN = 9001;
    private FirebaseAuth mAuth;
    private ProgressDialog pDialog;
    private GoogleSignInClient mGoogleSignInClient;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SignInButton signInButton = findViewById(R.id.sign_in_button);
        Button signOutButton = findViewById(R.id.sign_out_button);
        pDialog = new ProgressDialog(MainActivity.this);
 
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
 
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
 
        mAuth = FirebaseAuth.getInstance();
 
        signInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signIn();
            }
        });
        signOutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOut();
            }
        });
    }
 
    /**
     * Display Progress bar while Logging in
     */
 
    private void displayProgressDialog() {
        pDialog.setMessage("Logging In.. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
 
    }
 
    @Override
    public void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        updateUI(currentUser);
    }
 
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
 
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
 
        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                // ...
            }
        }
    }
 
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        displayProgressDialog();
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
 
        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()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(getApplicationContext(), "Login Failed: ", Toast.LENGTH_SHORT).show();
                        }
 
                        hideProgressDialog();
                    }
 
                });
    }
 
    private void updateUI(FirebaseUser user) {
        hideProgressDialog();
 
        TextView displayName = findViewById(R.id.displayName);
        ImageView profileImage = findViewById(R.id.profilePic);
        if (user != null) {
            displayName.setText(user.getDisplayName());
            displayName.setVisibility(View.VISIBLE);
            // Loading profile image
            Uri profilePicUrl = user.getPhotoUrl();
            if (profilePicUrl != null) {
                Glide.with(this).load(profilePicUrl)
                        .into(profileImage);
            }
            profileImage.setVisibility(View.VISIBLE);
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_button).setVisibility(View.VISIBLE);
        } else {
            displayName.setVisibility(View.GONE);
            profileImage.setVisibility(View.GONE);
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_button).setVisibility(View.GONE);
        }
    }
 
    private void hideProgressDialog() {
        pDialog.dismiss();
    }
 
    private void signOut() {
        // Firebase sign out
        mAuth.signOut();
 
        // Google sign out
        mGoogleSignInClient.signOut().addOnCompleteListener(this,
                new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        updateUI(null);
                    }
                });
    }
 
}

Here, we check if the user is already logged in. If yes, then update the UI with profile picture and name of the user. Also, hide the Login button and display the Logout button. If the user is not logged in, then display only the Login button.

16. Now run the application on your emulator or device.

Demonstration

Below animation shows the demo of the app:

Sign In with Google Demo

Source Code and APK Files

You can download the Source code and APK files from the below links:

Download Source CodeDownload APK

If you have any doubts, then we can discuss them in the comments section. If you have liked this tutorial, please do follow us on Twitter and Facebook.

Stay Connected

No spam guarantee.

Sharing is caring!
  • 5
    • About
    •  
    • Latest Posts
    Abhishek

    Abhishek

    Abhishek loves coding. His favorite is Android Development. Apart from coding he loves traveling and reading.
    Posted in: Cloud ConnectivityFiled under: android, android application, android tutorial, glide, google auth, google login

    Post navigation

    ← Login and Registration in Android using PHP and MySQL
    Android: Uploading File to Server with Progress Bar 
이 게시물을...
목록
번호
제목
글쓴이
조회 수
추천 수
날짜
58 node.js와 socketIO를 이용한 채팅 프로그램 제작시 아이폰 소켓끊김현상
admin
9466   2019-06-06
 
57 objective c parse json from url request dispatch_async
admin
10027   2019-06-06
 
56 JSON Parsing in Objective-C 제이슨 파싱 NSDictionary NSArray valueForKey
admin
10110   2019-06-06
 
55 [IOS] Json 형태의 스트링을 NSDictionary 로 변환 파싱 objectForKey
admin
9342   2019-06-06
 
54 Objective c parse json from url request
admin
9030   2019-06-03
 
53 [iPhone] HTTP Request/Response Wrapper 클래스 만들기 매우 잘된 설명
admin
8906   2019-05-21
 
52 Creating an NSObject that makes REST API calls (with threading)
admin
8982   2019-05-20
 
51 iOS NSURLConnection By Example
admin
9045   2019-05-20
 
50 objective c session post get방식
admin
9566   2019-05-20
 
49 Node.js + Express.js + Bootstrap(부트스트랩) 시작하기
admin
13807   2019-04-15
 
48 Android Asynchronous Http Client A Callback-Based Http Client Library for Android
admin
22153   2018-06-05
 
47 two simple AsyncTasks that use the updated JSONParser class login password
admin
10503   2018-05-10
 
46 HttpURLConnection post get JSONObject makeHttpRequest
admin
11297   2018-05-10
 
45 Android: How to parse JSON Array of Array of objects 제이슨 어레이 오브젝트 값 가져오기
admin
11258   2018-05-10
 
44 안드로이드 Reading JSON Write JSON
admin
30167   2018-05-07
 
Android: Login with Google Account
admin
12377   2018-05-07
http://www.androiddeft.com/2018/01/28/android-login-with-google-account/ In on of my previous article, I have explained how to implement login with Facebook. In this tutorial, we will see how can we authenti...  
42 Login and Registration in Android using PHP and MySQL
admin
29460   2018-05-07
 
41 JSON Parsing in Android over HTTP
admin
11098   2018-05-07
 
40 Android | Send “POST” JSON Data to Server
admin
147944   2018-05-07
 
39 Sending JSON Data to Server using Async Thread
admin
10569   2018-05-06
 
38 How do I send data to a Node.js server from an Android app?
admin
72491   2018-05-06
 
37 How To Make HTTP POST Request To Server - Android Example
admin
10707   2018-05-06
 
36 Android - Send a HTTP(S) POST request
admin
11772   2018-05-06
 
35 Android Fundamentals – AsyncTask Post
admin
10914   2018-05-06
 
34 Android JSON Parsing from REST Service Example Post Get
admin
11833   2018-05-06
 
33 Android OkHttp3 Http Get Post Request Example
admin
12885   2018-05-06
 
32 How to send HTTP GET / POST request in Java
admin
11515   2018-05-06
 
31 Android JSON Parsing from REST Service Example
admin
12010   2018-05-06
 
30 JSON Parsing in Android using Android Studio 기초 및 소스코드
admin
11104   2018-05-06
 
29 Android Asynchronous Http Client 안드로이드 클라이언트
admin
17250   2018-05-05
 
목록
쓰기
첫 페이지 1 2 끝 페이지
검색 취소

Powered by (주)제이에스솔루션 인터넷전화 070 가입자 가입 소프트웨어 개발