Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logout from Google Sign In Integration android

I am learning to implement Google Sign In Integration. I am following the demo from Google Developers. Here is my code for Login Page :

public class LoginActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

    private Button btnSignOut, btnDisconnect;
    private SignInButton btnSignIn;
    private ProgressDialog mProgressDialog;
    private static final String TAG = "LoginActivity";
    private TextView mStatusTextView;
    GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 9001;
    private Button btnNext;

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

        initInstances();

    }

    private void initInstances() {

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        mStatusTextView = (TextView) findViewById(R.id.status);
        btnSignOut = (Button) findViewById(R.id.sign_out_button);
        btnDisconnect = (Button) findViewById(R.id.disconnect_button);
        btnSignIn = (SignInButton) findViewById(R.id.sign_in_button);
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        btnSignIn.setScopes(gso.getScopeArray());


        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnDisconnect.setOnClickListener(this);

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        Log.d(TAG, "onConnectionFailed:" + connectionResult);
        Toast.makeText(LoginActivity.this, "" + connectionResult, Toast.LENGTH_SHORT).show();

    }

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

        OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        if (opr.isDone()) {
            // If the user's cached credentials are valid, the OptionalPendingResult will be "done"
            // and the GoogleSignInResult will be available instantly.
            Log.d(TAG, "Got cached sign-in");
            GoogleSignInResult result = opr.get();
            handleSignInResult(result);
        } else {
            // If the user has not previously signed in on this device or the sign-in has expired,
            // this asynchronous branch will attempt to sign in the user silently.  Cross-device
            // single sign-on will occur in this branch.
            showProgressDialog();
            opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
                @Override
                public void onResult(GoogleSignInResult googleSignInResult) {
                    hideProgressDialog();
                    handleSignInResult(googleSignInResult);
                }
            });
        }
    }

    private void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.hide();
        }
    }

    // [START onActivityResult]
    @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);
        }
    }

    private void handleSignInResult(GoogleSignInResult result) {
        Log.d(TAG, "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            GoogleSignInAccount acct = result.getSignInAccount();
            mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
            updateUI(true);
            //Log.d(TAG, "photoUrl "+result.getSignInAccount().getPhotoUrl());
            Intent iNext = new Intent(LoginActivity.this, ProfileInfoActiviy.class);

            iNext.putExtra("userId", acct.getId());
            iNext.putExtra("userName", acct.getDisplayName());
            if (acct.getPhotoUrl() != null) {
                iNext.putExtra("userPhoto", acct.getPhotoUrl().toString());
            }
            iNext.putExtra("userEmail", acct.getEmail());

            startActivity(iNext);

        } else {
            // Signed out, show unauthenticated UI.

            updateUI(false);
        }
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    // [START signOut]
    private void signOut() {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END signOut]

    // [START revokeAccess]
    private void revokeAccess() {
        Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        // [START_EXCLUDE]
                        updateUI(false);
                        // [END_EXCLUDE]
                    }
                });
    }


    private void updateUI(boolean signedIn) {
        if (signedIn) {
            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);
        }
    }

    private void intentToInfo() {
       /* Intent iNext=new Intent(LoginActivity.this,ProfileInfoActiviy.class);
        startActivityForResult(iNext,);*/
    }


    @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;

        }

    }

}

In the Google Developers demo, they have explained how to Sign Out but it is from within same activity. I want to logout from next/another activity which is as follows:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_info_activiy);
        ButterKnife.bind(this);

        String uId = getIntent().getExtras().getString("userId");
        String uName = getIntent().getExtras().getString("userName");
        String uEmail = getIntent().getExtras().getString("userEmail");
        if (getIntent().getExtras().getString("userPhoto") != null) {
            uPhoto = getIntent().getExtras().getString("userPhoto");
        }

        tvUserId.setText(uId);
        tvUserName.setText(uName);
        tvEmailId.setText(uEmail);

        loadImage(uPhoto);

        btnSignOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              Toast.makeText(ProfileInfoActiviy.this, "Logged Out" ,                                        Toast.LENGTH_SHORT).show();
            }
        });

I cant log out from here coz mGoogleApiClient will be null here. Any ideas??

like image 696
Nir Patel Avatar asked Mar 16 '16 05:03

Nir Patel


2 Answers

Put following code in any activity. Try this when user clicks on Logout Button:

 Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
               new ResultCallback<Status>() {
                   @Override
                   public void onResult(Status status) {


                   }
               });

put this in onCreate():

 mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API)
                .build();

then override onStart() like this

 @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }
like image 111
Parsania Hardik Avatar answered Sep 18 '22 11:09

Parsania Hardik


Best code to signout from Google is

 val gsoBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail()
      activity?.let {
              GoogleSignIn.getClient(it, gsoBuilder.build())?.signOut()
                                }
like image 20
IshRoid Avatar answered Sep 19 '22 11:09

IshRoid