Android Class for Google Login

Google Sample

Import Classes

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;

Implement View.OnClickListener

/**
 * Activity to demonstrate basic retrieval of the Google user's ID, email address, and basic
 * profile.
 */
public class SignInActivity extends AppCompatActivity implements
        View.OnClickListener {

Set up Java classes for login

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Button listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

        // Configure sign-in to request the user's ID, email address, and basic
        // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(currentFragment.getString(R.string.google_login_web_client_id))
                .requestEmail()
                .build();
        // Build a GoogleSignInClient with the options specified by gso.
        mGoogleSignInClient = GoogleSignIn.getClient(currentActivity, gso);
    }

and


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                signIn();
                break;
            case R.id.sign_out_button:
                signOut();
                break;
            case R.id.disconnect_button:
                revokeAccess();
                break;
        }
    }

Use existing login if previously logged in

    @Override
    public void onStart() {
        super.onStart();

        // [START on_start_sign_in]
        // Check for existing Google Sign In account, if the user is already signed in
        // the GoogleSignInAccount will be non-null.
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        updateUI(account);
        // [END on_start_sign_in]
    }

Method Signin

    // [START signIn]
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signIn]

and

    // [START onActivityResult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            // The Task returned from this call is always completed, no need to attach
            // a listener.
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }
    // [END onActivityResult]

    // [START handleSignInResult]
    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);

            // Signed in successfully, show authenticated UI.
            updateUI(account);
        } catch (ApiException e) {
            // The ApiException status code indicates the detailed failure reason.
            // Please refer to the GoogleSignInStatusCodes class reference for more information.
            Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
            updateUI(null);
        }
    }
    // [END handleSignInResult]

Method Signout

    // [START signOut]
    private void signOut() {
        mGoogleSignInClient.signOut()
                .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        // [START_EXCLUDE]
                        updateUI(null);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END signOut]

Method revokeAccess

    // [START revokeAccess]
    private void revokeAccess() {
        mGoogleSignInClient.revokeAccess()
                .addOnCompleteListener(this, new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        // [START_EXCLUDE]
                        updateUI(null);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END revokeAccess]

Updating UI on login

    private void updateUI(@Nullable GoogleSignInAccount account) {
        if (account != null) {
            mStatusTextView.setText(getString(R.string.signed_in_fmt, account.getDisplayName()));

            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
        } else {
            mStatusTextView.setText(R.string.signed_out);

            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

Communicating login to backend server

    private void communicateLogin2BackendServer(@Nullable GoogleSignInAccount account) {
            String googleIdToken = account.getIdToken();
            String accountEmail = account.getEmail();
            //txtGoogleLoggedInUser.setText(accountEmail);
            currentFragment.updateUIEmail(accountEmail);
            Log.w(TAG, "Logged in!! updateUI: "+account.getEmail() +
                    " id token is " + googleIdToken
            );
            Boolean purposeCheck = purposeOfActivity.equals("GOOGLE_LOGIN_TO_WEBSITE") || purposeOfActivity.equals("RE_GOOGLE_LOGIN_TO_WEBSITE");
            Log.w(TAG, "updateUI: Logged purposeOfActivity " + purposeOfActivity );
            Log.w(TAG, "updateUI: Logged purposeCheck " + purposeCheck +
                        getClass().getName() + " " +Thread.currentThread().getStackTrace()[2].getLineNumber());

            if(purposeCheck)
            {
                Log.w(TAG, "updateUI: returning after Logged in" );

                /*Intent intent = new Intent();
                intent.putExtra(Intent.EXTRA_TEXT, googleIdToken);
                setResult(RESULT_OK, intent);
                finish();// close this activity*/
                //https://stackoverflow.com/a/69630283
                Bundle bundle = new Bundle();
                bundle.putString("LOGIN_TYPE", "GOOGLE");
                bundle.putString("GOOGLE_ID_TOKEN", googleIdToken);
                bundle.putString("PURPOSE_OF_CALL", "RETURN_AFTER_GOOGLE_LOGIN");

                /*NavHostFragment.findNavController(SecondFragment.this)
                        .navigate(R.id.action_SecondFragment_to_FirstFragment,bundle);*/
                currentFragment.go2FirstFragment(bundle);
                // to retrieve in next fragment getArguments().getString("GOOGLE_ID_TOKEN")
            }//if(purposeOfActivity == "GOOGLE_LOGIN_TO_WEBSITE")
    }

USing Weview to Communicate Login to Backend

Method setWebView will be called in onStart of FirstFragment


    private void setWebView(/*Bundle savedInstanceState*/)
    {

        /*
        For Adding WebView https://developer.android.com/develop/ui/views/layout/webapps/webview
        
Android App Development : Quick Tips
1. Add WebView in layout 2. Add permissions in AndroidManifest.xml 3. Set WebSettings for enabling javascript operations 4. Add WebAppInterface4CallsFromJS (custom object) as interface for web page to android app 5. Add WebViewClient for handling events that impact content rendering. You can also use this subclass to intercept URL loading. 6. Add WebChromeClient for showing onConsoleMessage in logcat, enable fullscreen display. 7. Add DownloadListener for downloading eg: pdfs etc */ myWebViewHelper = new WebViewHelper((AppCompatActivity) getActivity(),binding.webViewMain); myWebViewHelper.setCalledFromFragment(this); // get the GOOGLE_ID_TOKEN from SecondFragment Bundle bundle = getArguments(); if(bundle != null) { String loginType = bundle.getString("LOGIN_TYPE"); myWebViewHelper.setLoginType(loginType); if(loginType != null) { switch (loginType) { case "GOOGLE": String googleIdTokenReceived = bundle.getString("GOOGLE_ID_TOKEN"); myWebViewHelper.setGoogleIdToken(googleIdTokenReceived); break; case "FACEBOOK": String facebookAccessTokenReceived = bundle.getString("FACEBOOK_ACCESS_TOKEN"); myWebViewHelper.setFacebookAccessToken(facebookAccessTokenReceived); break; } } } myWebViewHelper.setWebView(); if(currentPertinantURL == null) { Log.i(TAG, "currentPertinantURL is " + currentPertinantURL + " so Loading home page"); myWebViewHelper.loadHomePage(); } else { Log.i(TAG, "currentPertinantURL is " + currentPertinantURL ); myWebViewHelper.loadURL(currentPertinantURL); } }