Sunday, January 8, 2017

Simple Android Tutorial Login Using Google Account

Now days, much of application work with required create an account, there are lot of way to create an account to the apps : Using valid email, Facebook  and etc.

Generally, those who develop an apps using Facebook and Google as the way to register beside the valid email.


The information that taken from Google and Facebook generally are name of account, email, profile picture and other public information.

Beside that, you also can post something to your Facebook home from your android application. I will post this topic soon. Interesting right?

For use your google account, you have to had Google email. After that fill the public information in your Google + account.

See also : Simple Android Tutorial Login Using Facebook Account

but, i think all of us have been had a Google plus account, right? So let start the implementation Login using Google plus account.

1. COMPILE THE LIBRARIES

Compile the following libraries in your build.gradle (Module : app):

dependencies {
.
.
.
compile 'com.google.android.gms:play-services-auth:9.0.2' // add this line for google login
compile 'com.github.bumptech.glide:glide:3.7.0' // add this for glide
}
apply plugin: 'com.google.gms.google-services' //add this line for google
view raw build.gradle hosted with ❤ by GitHub
In your build.gradle (Project : YourProjectName),  paste the classpath below :

classpath 'com.google.gms:google-services:3.0.0'

2. REGISTER YOUR PACKAGE NAME AND SHA-1 KEY

Actually this step for get the google-service.json. To get that file, you have to register your package project's name and SHA-1 key.

First find your SHA-1 key, take a look at the Figure 1 :

Figure 1

Guideline :

  1. Klik Gradle tab on the right side of your android studio IDE
  2. Klik the icon Refresh all the gradle projects
  3. Open :app/task/android/signingReport. Double click of signingReport.
  4. Your SHA-1 Key appears on the console.

Afte you find your SHA-1 Key, Open Developers.google console. Create new project or your can use your existing project.

To generating the google.service.json, just follow the figures below :

Figure 1

Guideline Figure 1 :
  1. Choose your project name (or create new one)
  2. Paste your package name
  3. Click the button Choose and configure services ~>

Figure 2

Guidelines fFigure 2 :
  1. Choose Google SignIn Mode
  2. Paste your SHA-1 Key
  3. Click Enable Google Sign In

Figure 3

Guideline Figure 3 :
  1. Just click the button Generate configuration files

Figure 4

Guideline Figure 4 :
  1. Download the google-service.json and place inside folder app in you directory project. Take a look at the figure 5

Figure 9

After that create your layout xml. Just simple layout for this tutorial. in this project i labelled as activity_google_login.xml. Here its code :

<?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:id="@+id/activity_google_login"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.androidbie.googlelogintutorial.GoogleLoginActivity">
<LinearLayout
android:layout_width="match_parent"
android:clickable="true"
android:background="@android:color/holo_red_dark"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_sign_in_google"
android:layout_width="match_parent"
android:background="?attr/selectableItemBackground"
android:textColor="@android:color/white"
android:text="Google Login"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:layout_marginTop="30dp"
android:id="@+id/imageview_profile_pict"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<TextView
android:id="@+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center"/>
<LinearLayout
android:layout_width="wrap_content"
android:clickable="true"
android:background="@android:color/holo_red_dark"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_log_out_google"
android:layout_width="wrap_content"
android:background="?attr/selectableItemBackground"
android:textColor="@android:color/white"
android:text="Logout"
android:visibility="gone"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
In your java class, there several steps that you have to know, there are :

Google Sign Options

//google signin option
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail().build();

Google Api Client

//set google api

googleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this,this) /*activity, onConnectionFailedListener*/        
        .addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
        .build();

Method getCachange()

The flow of this method is, in case the users have logged in, when they open the apps again, user no need to login again because method getCache() will displaying the information. The point is, this method will work if the users don't logout the apps before.

/**
* this method used to get the cache if you have logged or not before.
*/
private void getCache(){
OptionalPendingResult<GoogleSignInResult> optionalPendingResult= Auth.GoogleSignInApi.silentSignIn(googleApiClient);
if(optionalPendingResult.isDone()){
GoogleSignInResult result = optionalPendingResult.get();
handleSignInResult(result);
}else{
optionalPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(@NonNull GoogleSignInResult result) {
handleSignInResult(result);
}
});
}
}
view raw getCache().java hosted with ❤ by GitHub
Method HandleSignInResult()

After login, this method will set the display name and profile picture on you application. Glide will uses as the Image Loader from URL.


/**
* this method used to handle of your account after logged
* @param result
*/
private void handleSignInResult(GoogleSignInResult result){
if(result.isSuccess()){
updateUI(true);
progressDialog.dismiss();
//hide and show button login and logout
btnSignInGoogle.setVisibility(View.GONE);
btnSignOutGoogle.setVisibility(View.VISIBLE);
GoogleSignInAccount account = result.getSignInAccount();
//set name and photo profile
tvName.setText(account.getDisplayName());
Glide.with(this)
.load(account.getPhotoUrl())
.into(ivProfile);
}else{
progressDialog.dismiss();
}
}
That's the main step that you have to know. Maybe the code above is still unclear for you, so the follows is the full code of java classes :

package com.androidbie.googlelogintutorial;
import android.app.ProgressDialog;
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.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
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.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
public class GoogleLoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
public static final int LOGIN_GOOGLE_NUMBER=012;
private Button btnSignInGoogle;
private Button btnSignOutGoogle;
private TextView tvName;
private ImageView ivProfile;
private ProgressDialog progressDialog;
//google attribute
private GoogleApiClient googleApiClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_login);
btnSignInGoogle = (Button) findViewById(R.id.btn_sign_in_google);
tvName = (TextView) findViewById(R.id.textview_name);
ivProfile = (ImageView) findViewById(R.id.imageview_profile_pict);
btnSignOutGoogle = (Button) findViewById(R.id.btn_log_out_google);
//set progressDialog
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Login Using Google");
//google signin uption
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail().build();
//set google api
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this) /*activity, onConnectionFailedListener*/
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
btnSignInGoogle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.show();
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, LOGIN_GOOGLE_NUMBER);
}
});
btnSignOutGoogle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog.setMessage("Logout");
progressDialog.show();
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
if(status.isSuccess()){
progressDialog.dismiss();
updateUI(false);
Toast.makeText(GoogleLoginActivity.this, "Logout successful", Toast.LENGTH_SHORT).show();
}else {
progressDialog.dismiss();
Toast.makeText(GoogleLoginActivity.this, "Logout failed", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
protected void onStart() {
super.onStart();
getCache();
}
/**
* this method used to get the cache if you have logged or not before.
*/
private void getCache(){
OptionalPendingResult<GoogleSignInResult> optionalPendingResult= Auth.GoogleSignInApi.silentSignIn(googleApiClient);
if(optionalPendingResult.isDone()){
GoogleSignInResult result = optionalPendingResult.get();
handleSignInResult(result);
}else{
optionalPendingResult.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(@NonNull GoogleSignInResult result) {
handleSignInResult(result);
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==LOGIN_GOOGLE_NUMBER){
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
/**
* this method used to handle of your account after logged
* @param result
*/
private void handleSignInResult(GoogleSignInResult result){
if(result.isSuccess()){
updateUI(true);
progressDialog.dismiss();
//hide and show button login and logout
btnSignInGoogle.setVisibility(View.GONE);
btnSignOutGoogle.setVisibility(View.VISIBLE);
GoogleSignInAccount account = result.getSignInAccount();
//set name and photo profile
tvName.setText(account.getDisplayName());
Glide.with(this)
.load(account.getPhotoUrl())
.into(ivProfile);
}else{
progressDialog.dismiss();
}
}
/**
* this method used to update visible or gone of user interface
* @param statusLogin
*/
private void updateUI(boolean statusLogin){
if(statusLogin==true){
btnSignInGoogle.setVisibility(View.GONE);
btnSignOutGoogle.setVisibility(View.VISIBLE);
}else{
btnSignInGoogle.setVisibility(View.VISIBLE);
btnSignOutGoogle.setVisibility(View.GONE);
ivProfile.setVisibility(View.GONE);
tvName.setVisibility(View.GONE);
}
}
}

Download the project by clicking the following button :


Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)