Google+ sign out from a different activity

28,638

Solution 1

Just add this on your new activity, where you want your logout-button for google+ to be there :

@Override
protected void onStart() {
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
    super.onStart();
}

and next:

 signout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                  new ResultCallback<Status>() {
                      @Override
                      public void onResult(Status status) {
                          // ...
                          Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_SHORT).show();
                          Intent i=new Intent(getApplicationContext(),MainActivity.class);
                          startActivity(i);
                      }
                  });
      }
  });

Solution 2

Hey i solved this problem by myself, working like charm

What is the problem : Google plus signIn in one activity but need to Logout from another activity

Solution:

My Google-plus Logout Activity is like this:

public class MainActivity extends Activity implements OnClickListener,
    ConnectionCallbacks, OnConnectionFailedListener,
    ResultCallback<People.LoadPeopleResult> {

   GoogleApiClient mGoogleApiClient;
   boolean mSignInClicked;

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

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();

     //copy this code on "Logout" Onclick
  logout.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            // updateUI(false);
            System.err.println("LOG OUT ^^^^^^^^^^^^^^^^^^^^ SUCESS");
        } 

        }
    });

}
@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    mSignInClicked = false;

    // updateUI(true);
    Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(
            this);
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub
    mGoogleApiClient.connect();
    // updateUI(false);
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onResult(LoadPeopleResult arg0) {
    // TODO Auto-generated method stub

}

Description about solution:

For single package google plus API will generate one token & session.Just here simply make one more session in logout page also.You can easily logout from session now

I to have tried a lot about this problem,to logout from current session, just try this .it will definitely work. any doubts let me know

Solution 3

It would probably be easier to create a base class and inherit the connect/disconnect methods. Photohunt, our full sample, documents this design in detail.

Docs Code

Solution 4

After struggling for over a week to find out the answer. I did this, After signing in save boolean isSignedIn in sharedpreferences as true.

private SharedPreferences.Editor editor;
private SharedPreferences prefs;

editor = getSharedPreferences(getString(R.string.userDetails), MODE_PRIVATE).edit();
editor.putBoolean(getString(R.string.isSignedIn), true);
editor.apply();`

Now from any activity when the user clicks logout, change the boolean to false.

In your Login Activity where googleApiClient is build. In its onStart method. Check if isSignedIn is false.

@Override
public void onStart() {
super.onStart();
if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
    signOut();
    }     
}

Do the same in onConnected

@Override
public void onConnected(Bundle connectionHint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG, "onConnected: " + "yes it is connected");
        if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
            signOut();
        }
    }
}

This will logout and revokeAccess.

public void signOut() {
    if (mGoogleApiClient != null) {
        Log.e(TAG, "signOut: " + mGoogleApiClient + mGoogleApiClient.isConnected());
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
        if (mGoogleApiClient.isConnected()) {
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // ...
                            Log.i(TAG, "onResult: " + mGoogleApiClient);
                        }
                    });
         Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            Log.i(TAG, "onResult: Revoke Access status:" + status.getStatus());
                        }
                    });
        }
    }
}

Solution 5

You can get instance of FirebaseAuth anywhere from the app as FirebaseAuth is a singleton class.

 mAuth = FirebaseAuth.getInstance();
 mAuth.signOut();
Share:
28,638
arielschon12
Author by

arielschon12

Updated on June 06, 2020

Comments

  • arielschon12
    arielschon12 almost 4 years

    I have started using the Google+ API for android, and I have created a sign-in application following this tutorial:

    https://developers.google.com/+/mobile/android/sign-in

    Now, the problem is that I want to create the sign out button from a different Activity, and what i tried to do didn't really worked..

    My GPlusLogin code (Activity for the Google+ Login):

    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.content.IntentSender.SendIntentException;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import com.google.android.gms.common.*;
    import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
    import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
    import com.google.android.gms.plus.PlusClient;
    
    public class GPlusLogin extends Activity implements ConnectionCallbacks, OnConnectionFailedListener{
    
        private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
        private static final String TAG = "GPlusLogin";
    
        private ProgressDialog mConnectionProgressDialog;
        private PlusClient mPlusClient;
        private ConnectionResult mConnectionResult;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.gplus_layout);
            mPlusClient = new PlusClient.Builder(this, this, this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
            Bundle extras = getIntent().getExtras();
            mConnectionProgressDialog = new ProgressDialog(this);
            mConnectionProgressDialog.setMessage("Signing in...");
    
            if(extras!=null){
                if(extras.getString("signout")!=null){
                    if (mPlusClient.isConnected()) {
                        mPlusClient.clearDefaultAccount();
                        mPlusClient.disconnect();
                        mPlusClient.connect();
                        finish();
                        startActivity(getIntent());
                    }
                }
            }else{
    
                findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {
    
                    public void onClick(View view) {
                        // TODO Auto-generated method stub
                        if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
                            if (mConnectionResult == null) {
                                mConnectionProgressDialog.show();
                            } else {
                                try {
                                    mConnectionResult.startResolutionForResult(GPlusLogin.this, REQUEST_CODE_RESOLVE_ERR);
                                } catch (SendIntentException e) {
                                    // Try connecting again.
                                    mConnectionResult = null;
                                    mPlusClient.connect();
                                }
                            }
                        }
                    }
                });
            }
        }
    
        @Override
        protected void onStart() {
            // TODO Auto-generated method stub
            super.onStart();
            mPlusClient.connect();
        }
    
        @Override
        protected void onStop() {
            // TODO Auto-generated method stub
            super.onStop();
            mPlusClient.disconnect();
        }
    
        @Override
        public void onConnectionFailed(ConnectionResult result) {
            // TODO Auto-generated method stub
            if (mConnectionProgressDialog.isShowing()) {
                // The user clicked the sign-in button already. Start to resolve
                // connection errors. Wait until onConnected() to dismiss the
                // connection dialog.
                if (result.hasResolution()) {
                    try {
                        result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
                    } catch (SendIntentException e) {
                        mPlusClient.connect();
                    }
                }
            }
    
            mConnectionResult = result;
        }
    
        @Override
        protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
            if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
                mConnectionResult = null;
                mPlusClient.connect();
            }
        }
    
        @Override
        public void onConnected() {
            // TODO Auto-generated method stub
            mConnectionProgressDialog.dismiss();
            Intent main = new Intent(GPlusLogin.this, MainActivity.class);
            main.putExtra("result", true);
            startActivity(main);
        }
    
        @Override
        public void onDisconnected() {
            // TODO Auto-generated method stub
            Log.d(TAG, "disconnected");
        }
    
    }
    

    My Disconnect code on MainActivity:

    import android.os.Bundle;
    import android.app.Activity;
    import android.content.Intent;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.TextView;
    
    
    public class MainActivity extends Activity{
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Bundle extras = getIntent().getExtras();
            if(extras==null){
                Intent intent = new Intent(this, GPlusLogin.class);
                startActivity(intent);
            }
            TextView text1 = (TextView) findViewById(R.id.text1);
            text1.setText("You Are Connected :D");
    
            Button SignOut = (Button) findViewById(R.id.sign_out_gplus);
            SignOut.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    Intent intent = new Intent(MainActivity.this, GPlusLogin.class);
                    intent.putExtra("signout", true);
                    startActivity(intent);
                }
            });
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
    
    }