In this article I will explain how to add a simple Google sign in button to your android application.
Step 1: Create a android application using Andriod studio
Create a simple project using andriod studio. be mindful about the package name of the application as you will have to add it when registering the app with google
Step 2:Create a project with google fire base console
Go to https://console.firebase.google.com and login with your google account. Once you logged in select add project
Then give your app a name
In the next step you can choose to setup google analytics for your app. For the simplicity i will select the option Not right now and click on create project
It will take couple of seconds to generate the project. After that you will see the below screen. Click continue button
Step 3: Setup the project in firebase
Once you finished with step 2 , you will be redirected to firebase homepage. Then select project overview -> project settings
Then you will be redirected to project general project settings page. Under project general tab set the support email . This is a compulsory field otherwise you will get errors when trying to login.
After that you can select the application type as Android
After that you will be redirected to register app window and please enter below details as per your application.
- Android package name : You can take this from the sample android project that you have created. Go to manifest -> AndroidManifes.xml in your project and search for package and copy that value
- App nick name : you can give a nick name to your app
- SHA-1 for your app : There are several ways to generate sha-1 for application. The easiest is to generate it using android studio. SHA-1 can generated as shown below
put these values and click on register app button. It will take couple of seconds to generate the project and then it will ask you to download google-services.json for you application. Download and put it in you app directory for the project. the finish the registration.
Step 4 : Set privacy in google console
You will have to set up privacy links and support email and privacy links in google developer console. Otherwise might get the exception mentioned in here.
Go to https://console.developers.google.com/apis
To project that you have created in firebase console should appear there. Select the project and select credential link. Then go to oAuth consent screen tab and enter application logo , support email , application home page link , application privacy policy link. Other details are optional and click save.
Now its time to write some code.
Step 5 : Including it in your application
- First add google dependency.Add the following in project level build.gradle
buildscript { repositories { google()
- Add the following dependency in app level build.gradle
implementation 'com.google.android.gms:play-services-auth:15.0.1'
- Add the google signin button to your activity
<?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=".SimpleSignin"> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.constraint.ConstraintLayout>
After you add the signin button it should look like below.
Modify your main activity and configure google signin as mentioned in the below code snippet
- Create a GoogleSignInOptions object configure which information you will be requesting from google.
- Add the click listener to google signin button and handle the click action
private SignInButton googleSignInButton; private GoogleSignInClient googleSignInClient; private static final int RC_SIGN_IN = 100;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple_signin); googleSignInButton = findViewById(R.id.sign_in_button); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); googleSignInClient = GoogleSignIn.getClient(this, gso); googleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent signInIntent = googleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } }); }
Once the button is clicked User is prompted with a dialog to select the Account he was log into.
The result of startActivityForResult will call back to method onActivityResult. We will override the onActivityResult method in our activity as below.
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); handleSignInResult(task); } }
You can implement your own method by replacing handleSignInResult and handle your application logic accordingly. As an example I have created my method to read the users display name and print it on the console
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); System.out.println(">>>>>>>" + account.getDisplayName()); } catch (ApiException e) { Log.w(TAG, "signInResult:failed code=" + e.getStatusCode()); e.printStackTrace(); } }
Checking for already logged in Users
In your application you might not want to prompt in the signin window each time the user launch the app. Also once the user signed in to your application he wont be signing out when the user closes the application. To handle this situation you might want to check whether the user is already logged in to your application. You can handle that with the below code snippet. Simply override onStart method in your activity.
@Override public void onStart() { super.onStart(); GoogleSignInAccount alreadyloggedUser = GoogleSignIn.getLastSignedInAccount(this); if (alreadyloggedUser != null) { Toast.makeText(this, "Already Logged In", Toast.LENGTH_SHORT).show(); } else { Log.d(TAG, "Not logged in"); } }
You can download the working sample from here