The Google API is used to integrate the Google Sign-In functionality in an Android application. To log in to an Android App using Google account, we need to integrate the Google API in the Android app. For doing this, it is necessary to configure the app to the Google developer account. For the Android application, we also need to download the ‘google-service.json’ file.
To configure the Android App on Google Developer Account:
- A Google developer account needs to be created at https://developers.google.com/identity/sign-in/android/start-integrating.
- Click on the ‘GET A CONFIGURATION FILE’ button.
- Enter the Project Name.
- Accept the Terms of Service.
- Click on the ‘Next’ button.
- Fill all the details to Configure your OAuth Client.
- Provide the signing certification SHA-1 key of the application.
- We can generate the certification SHA-1 key in either of the two ways:
- By using the command prompt.
- By Android Studio.
- By using the command prompt:
- Windows:
keytool -exportcert -list -v \ -alias androiddebugkey -keystore %USERPROFILE%\.android\debug.keystore
- Windows:
-
- Mac/Linux:
keytool -exportcert -list -v \ -alias androiddebugkey -keystore ~/.android/debug.keystore
- Mac/Linux:
- By Android Studio:
- Open the Android project.
- From the right-side panel, open the Gradle tab.
- Click on the ‘signingReport’ button twice.
- The app SHA-1 key will be available on the ‘Gradle Console’.
- Click on the Create button.
Example:
In the below example, we are integrating the Google Sign-In in the Android app so that the user successfully login through Google Sign-In. After which we will redirect to the next activity, i.e., ProfileActivity to retrieve the user details. In the Android project app directory, we will first paste the downloaded ‘google-services.json’ file.
Required Permission:
In the AndroidManifest.xml file, we will write the code to add the Internet permission.
<uses-permission android:name="android.permission.INTERNET" /> |
build.gradle (Project):
In the build.gradle file, we will write the code to add the following dependency.
dependencies{ classpath 'com.google.gms:google-services:3.1.0' } |
build.gradle(Module):
dependencies { implementation 'com.google.android.gms:play-services-auth:11.6.0' implementation 'com.github.bumptech.glide:glide:3.7.0' } apply plugin: 'com.google.gms.google-services' |
activity_main.xml:
In the activity_main.xml file, we will write the code to add the TextView and the Google SignIn Button.
Code:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:textSize="20dp" android:text="Sign in to move to the next activity." /> <com.google.android.gms.common.SignInButton android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sign_in_button" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_alignParentBottom="true" android:layout_marginBottom="20dp"> </com.google.android.gms.common.SignInButton> </RelativeLayout> |
MainActivity.java:
In the MainActivity.java file, we will write the code to call the Auth.GoogleSignInApi.getSignInIntent() method. This method is used to log in through Google Sign-In API. The unimplemented method onConnectionFailed(ConnectionResult) is overridden by the GoogleApiClient.OnConnectionFailedListener interface of Google API. This will return the connection failure result. To manage the connection between an Android application and Google Sign-In API, the GoogleApiClient class is used.
Code:
package com.example.radioapp; 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.TextView; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; 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; public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { SignInButton signInButton; private GoogleApiClient googleApiClient; TextView textView; private static final int RC_SIGN_IN = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); googleApiClient=new GoogleApiClient.Builder(this) .enableAutoManage(this,this) .addApi(Auth.GOOGLE_SIGN_IN_API,gso) .build(); signInButton=(SignInButton)findViewById(R.id.sign_in_button); signInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); startActivityForResult(intent,RC_SIGN_IN); } }); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==RC_SIGN_IN){ GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); handleSignInResult(result); } } private void handleSignInResult(GoogleSignInResult result){ if(result.isSuccess()){ gotoProfile(); }else{ Toast.makeText(getApplicationContext(),"Sign in cancel",Toast.LENGTH_LONG).show(); } } private void gotoProfile(){ Intent intent=new Intent(MainActivity.this,ProfileActivity.class); startActivity(intent); } } |
activity_profile.xml:
In the activity_profile.xml file, we will write the code to add the below component.
Code:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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=".ProfileActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <ImageView android:layout_width="80dp" android:layout_height="80dp" android:id="@+id/profileImage" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/name" android:text="name" android:textSize="20dp" android:layout_marginTop="20dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/email" android:textSize="20dp" android:text="email" android:layout_marginTop="20dp"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/userId" android:textSize="20dp" android:text="id" android:layout_marginTop="20dp"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/logoutBtn" android:text="Logout" android:layout_marginTop="30dp"/> </LinearLayout> </RelativeLayout> |
ProfileActivity.java:
In the ProfileActivity.java file, we will write the code to display the user detail after the successful login. When the user successfully login, the user details will be retrieved. The final result of invoking an API method of Google Play Services is represented by the Result interface implemented by the GoogleSignInResult class. The basic information of the user is held by the GoogleSignInAccount class.
Code:
package com.example.radioapp; 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.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 ProfileActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener { Button logoutBtn; TextView userName,userEmail,userId; ImageView profileImage; private GoogleApiClient googleApiClient; private GoogleSignInOptions gso; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); logoutBtn=(Button)findViewById(R.id.logoutBtn); userName=(TextView)findViewById(R.id.name); userEmail=(TextView)findViewById(R.id.email); userId=(TextView)findViewById(R.id.userId); profileImage=(ImageView)findViewById(R.id.profileImage); gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); googleApiClient=new GoogleApiClient.Builder(this) .enableAutoManage(this,this) .addApi(Auth.GOOGLE_SIGN_IN_API,gso) .build(); logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { if (status.isSuccess()){ gotoMainActivity(); }else{ Toast.makeText(getApplicationContext(),"Session not close",Toast.LENGTH_LONG).show(); } } }); } }); } @Override protected void onStart() { super.onStart(); OptionalPendingResult<GoogleSignInResult> opr= Auth.GoogleSignInApi.silentSignIn(googleApiClient); if(opr.isDone()){ GoogleSignInResult result=opr.get(); handleSignInResult(result); }else{ opr.setResultCallback(new ResultCallback<GoogleSignInResult>() { @Override public void onResult(@NonNull GoogleSignInResult googleSignInResult) { handleSignInResult(googleSignInResult); } }); } } private void handleSignInResult(GoogleSignInResult result){ if(result.isSuccess()){ GoogleSignInAccount account=result.getSignInAccount(); userName.setText(account.getDisplayName()); userEmail.setText(account.getEmail()); userId.setText(account.getId()); try{ Glide.with(this).load(account.getPhotoUrl()).into(profileImage); }catch (NullPointerException e){ Toast.makeText(getApplicationContext(),"image not found",Toast.LENGTH_LONG).show(); } }else{ gotoMainActivity(); } } private void gotoMainActivity(){ Intent intent=new Intent(this,MainActivity.class); startActivity(intent); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } } |