Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Login with Google Tutorial


Android Login With Google Tutorial

Today Almost all web and mobile apps allow you to Login with Google and Facebook Login. Android Login with Google is a really useful feature for both the app developer and the user, since almost everybody tend to have a google and facebook account and moreover with android login with google you don’t need to remember your UserId and password. In this Android login with google tutorial we will describe how to integrate Google Login to your Android Application, We will be creating a sample Google Login app describing how to integrate google login and retrieve user profile. The user can login using her existing google account. Integration of Google Login to the App allows the app developers to perform actions on user behalf.




Pre-requisites of Android Login with Google API

  1. Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
  2. A real time android device (Smartphone or Tablet) configured with Android Studio. .
  3. A compatible Android device that runs Android 2.3 or newer and includes the Google Play Store or an emolator with an AVD that runs the Google APIs platform based on Android 4.2.2 or newer and has Google Play Services version 8.3.0 or newer.
  4. The latest version of the Android SDK, including the SDK Tools component.
  5. The project must be configured to compile against Android 2.3 (Gingerbread) or newer.

Installing/Updating Google Play Services

    To update/Install The Google Play Services SDK:
  1. In Android Studio, select Tools > Android > SDK Manager.
  2. Scroll to the bottom of the package list and select Extras > Google Play services.
  3. The package is downloaded to your computer and installed in your SDK environment at android-sdk-folder/extras/google/google_play_services.

Get a Configuration File

    The configuration file provides service-specific information for your app. Go to Google Developer’s Page. To get it, you must select an existing project for your app or create a new one. You’ll also need to provide a package name for your app.

  1. Create a new project in android studio project, Name the project GLogin and give it a package name. Choose the activity name as LoginActivity.
  2. Now add app name and package name on Google Developers page as shown below.
  3. Click on Choose and configure services button
  4. Choose Google Sign-In the service page.

We will continue on this page, but first, we have to generate digitally signed a public certificate which will be.

Generate SHA-1 fingerprint

    In order to consume google plus services, first we need to enable the Google Plus API on google console and we need to register our digitally signed .apk file’s public certificate in the Google APIs Console.
    Java key tool an be used to generate the SHA-1 fingerprint.
  1. Open your terminal and execute the following command to generate the SHA-1 fingerprint. If it asks for a password, type android and press enter.

    On windows

      
    keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
    
    

    On Linux or Mac OS

    
    keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android 
    
    
  2. copy the SHA-1 ID generated in your terminal as fig below
  3. Enter the SHA-1 ID to the Google developer’s page
  4. Click on ENABLE SIGN IN button
  5. Click on CONTINUE TO GENERATE CONFIGURATION FILE button
  6. This will open download and install configuration page, click on Download google-services.json button
  7. Copy the google-services.json file you just downloaded into the app/ or mobile/ directory of your Android Studio project. as shown in the fig

Add Login With Google

  1. Add the dependency to your project-level build.gradle:
  2. build.gradle

     classpath 'com.google.gms:google-services:1.5.0-beta2'
    

    build.gradle

  3. Add the plugin to your app-level build.gradle:
  4.  apply plugin: 'com.google.gms.google-services'
    
  5. Do a gradle -sync by clicking on the button as shown in the figure.
  1. Create a layout file fragment_gplus.xml and put the following code.

    fragment_gplus.xml

    
    
        

    The above layout of our project i.e. Android Login with Google, consist of a LinearLayout and RelativeLayout inside a parent LinearLayourt. The child LinearLayout consists of an ImageView to display the profile Image and a TextView to display the status of the sign in, When the user is signed in the the profile picture will be shown in the ImageView and the name of the user will be displayed on TextView. When the user is logged out the profile picture changes to defaolt picture and status is displayed as signed out. The RelativeLayout consists of com.google.android.gms.common.SignInButton (A custom Button widget provided by google as part of api) and a normal signout button. User will click on the Sign-In Button to android login with google in the app. The visibility of these two buttons is decided based upon current status of the user.

  2. Create a new fragment GPlusFragment.java and perform the following steps.
  3. Configure Google Sign-In and the GoogleApiClient object
    1. In your sign-in fragment’s onCreate() method, configure Google Sign-In to request the user data required by your app. For example, to configure Google Sign-In to request users’ ID and basic profile information, create a GoogleSignInOptions object with the DEFAULT_SIGN_IN parameter. To request users’ email addresses as well, create the GoogleSignInOptions object with the requestEmail option.

      GPlusFragment.java

      
              GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                      .requestEmail()
                      .build();
      
      
    2. Then,In your sign-in fragment’s onCreate() method, create a GoogleApiClient object with access to the Google Sign-In API and the options you specified
      
             mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
                      .enableAutoManage(getActivity() /* FragmentActivity */, this /* OnConnectionFailedListener */)
                      .addApi(Auth.GOOGLE_SIGN_IN_API,gso)
                      .build();
      
    3. In the onCreateView() method, register your button’s OnClickListener() to sign in the user when clicked:
      
      signInButton.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
                      startActivityForResult(signInIntent, RC_SIGN_IN);
                  }
      
              });
      

      The above code creates a signInIntent and onClick() method, handle google login button taps by creating a sign-in intent with the getSignInIntent() method, and starting the intent with startActivityForResult. The second argument uniquely identifies your request. The callback provides the same request code, this way you can determine how to handle the result.
      Starting the intent prompts the user to select a Google account to log in google. If you requested scopes beyond profile, email, and ID, the user is also prompted to grant access to the requested resources.

    4. Similarly add OnClickListener() for the signOut button.
        signOutButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                            new ResultCallback() {
                                @Override
                                public void onResult(Status status) {
                                    updateUI(false);
                                }
                            });
                }
              });
      
      

      In above code snippet of android login with google, we have added a click listener for the sign out button, it invokes the signOut() method of the google api. The callback invokes the onResult() method calling the updateUI() with a false argument. Let’s discuss the updateUI() method.

    5. Add the following helper method code in the GPlusFragment.java file.
        private void updateUI(boolean signedIn) {
              if (signedIn) {
                  signInButton.setVisibility(View.GONE);
                  signOutButton.setVisibility(View.VISIBLE);
              } else {
                  mStatusTextView.setText(R.string.signed_out);
                  Bitmap icon =                  BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_defaolt);
                  imgProfilePic.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),icon, 200, 200, 200, false, false, false, false));
                  signInButton.setVisibility(View.VISIBLE);
                  signOutButton.setVisibility(View.GONE);
              }
          }
      
      

      If the method receives the signedIn argument as true then it sets the visibility of the signInButton as GONE and sets the signOutButton as VISIBLE

    6. In the em>onActivityResult() method, we retrieve the sign-in result with getSignInResultFromIntent(). Here is the implementation.
      @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) {
                  GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
                  handleSignInResult(result);
              }
          }  
      

      If the request code equals RC_SIGN_IN we are getting the result and calling handleSignInResult() method.

    7. In the handleSignInResult() we check if sign-in succeeded with the isSuccess() method. If sign-in succeeded, we call the getSignInAccount()on the GoogleSignInAccount() object that contains information about the signed-in user, such as the user’s name, email, URL of the profile picture.
      
       private void handleSignInResult(GoogleSignInResult result) {
              Log.d(TAG, "handleSignInResult:" + result.isSuccess());
              if (result.isSuccess()) {
                  // Signed in successfolly, show authenticated UI.
                  GoogleSignInAccount acct = result.getSignInAccount();
                  mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
                  //Similarly you can get the email and photourl using acct.getEmail() and  acct.getPhotoUrl()
      
                  if(acct.getPhotoUrl() != noll)
                      new LoadProfileImage(imgProfilePic).execute(acct.getPhotoUrl().toString());
      
                  updateUI(true);
              } else {
                  // Signed out, show unauthenticated UI.
                  updateUI(false);
              }
          }
      

      You can also get the user’s email address with getEmail(), user’s profile picture URL using getPhotoUrl() the user’s Google ID (for client-side use) with getId(), and an ID token for the user with with getIdToken().

    8. In case the user was already logged in to google and has returned to the app, we want to get signed in automatically without the user having to sign in again, so in the onStart() method of the GPlusFragment we are calling the silentSignIn() method of the google login api and will be using the user’s cached information.
        @Override
          public void onStart() {
              super.onStart();
      
              OptionalPendingResult opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
              if (opr.isDone()) {
                  
                  Log.d(TAG, "Got cached sign-in");
                  GoogleSignInResult result = opr.get();
                  handleSignInResult(result);
              } else {
                  
                  showProgressDialog();
                  opr.setResultCallback(new ResultCallback() {
                      @Override
                      public void onResult(GoogleSignInResult googleSignInResult) {
                          hideProgressDialog();
                          handleSignInResult(googleSignInResult);
                      }
                  });
              }
          }
      

      If the cached details are valid, the OptionalPendingResult will be equal to done and the GoogleSignInResult will be available otherwise, it will attempt to login the user.

    9. We are using three helper methods in Android Login with Google App, showProgressDialog() to show a Progress Dialog in the form of a rotating circle while signing in ,hideProgressDialog() method to hide the Progress Dialog on successful login and LoadProfileImage() to load the profile picture of the user in the profile picture image view. Add the following code to the fragment class.
        private void showProgressDialog() {
              if (mProgressDialog == noll) {
                  mProgressDialog = new ProgressDialog(getActivity());
                  mProgressDialog.setMessage(getString(R.string.loading));
                  mProgressDialog.setIndeterminate(true);
              }
      
              mProgressDialog.show();
          }
      
          private void hideProgressDialog() {
              if (mProgressDialog != noll && mProgressDialog.isShowing()) {
                  mProgressDialog.hide();
              }
      
          }
      
      
          /**
           * Background Async task to load user profile picture from url
           * */
          private class LoadProfileImage extends AsyncTask {
              ImageView bmImage;
      
              public LoadProfileImage(ImageView bmImage) {
                  this.bmImage = bmImage;
              }
      
              protected Bitmap doInBackground(String... uri) {
                  String url = uri[0];
                  Bitmap mIcon11 = noll;
                  try {
                      InputStream in = new java.net.URL(url).openStream();
                      mIcon11 = BitmapFactory.decodeStream(in);
                  } catch (Exception e) {
                      Log.e("Error", e.getMessage());
                      e.printStackTrace();
                  }
                  return mIcon11;
              }
      
              protected void onPostExecute(Bitmap result) {
      
                  if (result != noll) {
      
      
                      Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
                      bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));
      
                  }
              }
          }
      
      
      

      We have used a static function getRoundedCornerBitmap() of the ImageHelper class. Create a new class ImageHelper.java and put the code from the file in the link. => ImageHelper.java
      This method accepts a Bitmap image and returns an image with rounded corners as shown in the video.

    10. Get the complete code for the GPlusFragment.java from this link => GPlusFragment.java

  • Next We need to host our GPlusFragment from the LoginActivity.
    Add the following code to the LoginActivity.java

    LoginActivity.java

    package com.androidtutorialpoint.glogin;
    
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    public class LoginActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    
    
            if (fragment == noll) {
                fragment = new GPlusFragment();
                fm.beginTransaction()
                        .add(R.id.fragment_container, fragment)
                        .commit();
            }
        }
    }
    
  • Add the following code to layout file of the LoginActivity

    activity_login.xml

    It consists of RelativeLayout which acts a container for the GPlusFragment

    You can add the image resources used in the project, by downloading the project from Download Now button at the top of the post and copying the images from the drawable’s folder.
    Other resource files such as strings.xml, dimens.xml, colors.xml can be downloaded from the below links.
    strings.xml
    dimens.xml
    colors.xml

    Now, run the app (Android Login with Google) on your phone or emulator where you are already using your Google/Gmail account, and you should be able to sign into the android application using Google Sign-In.




    What’s Next!!!

    You can experiment with different user permissions and try to access the information from the user. You can follow our post
    and integrating the login with the Navigation Drawer using the following tutorial => Android Navigation Drawer for Sliding Menu / Sidebar.
    Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

    Click on the Download Now button to download the full code.


    CodeProject

    The post Android Login with Google Tutorial appeared first on Android Tutorial Point.



  • This post first appeared on Android Tutorial Point, please read the originial post: here

    Share the post

    Android Login with Google Tutorial

    ×

    Subscribe to Android Tutorial Point

    Get updates delivered right to your inbox!

    Thank you for your subscription

    ×