4

Using such code it is possible to link my app and use account.

if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Plus.API)
                    .addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
        }
        mGoogleApiClient.connect();

But is where any way to 'logout' from this account once activated or switch to a new one?

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194

4 Answers4

18

clearDefaultAccount() doesn't work. For sign out and clear selected account use Auth.GoogleSignInApi.signOut() like this:

private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext()) //Use app context to prevent leaks using activity
            //.enableAutoManage(this /* FragmentActivity */, connectionFailedListener)
            .addApi(Auth.GOOGLE_SIGN_IN_API)
            .build();
}

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

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

private void signOut() {
    if (mGoogleApiClient.isConnected()) {
        Auth.GoogleSignInApi.signOut(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
    }
}
Gonzalo
  • 1,781
  • 15
  • 29
  • What I could understad, You are using `GoogleSignInApi` to sign in wich needs a `GoogleApiClient` instance, and you must be connect in order to work properly. So to really disconnect your account you must signout from `GoogleSignInApi` with your `GoogleApiClient` instance and reconnect. – Gonzalo Jul 25 '17 at 20:03
  • @Gonzalo Why have you added `mGoogleApiClient.disconnect();` and `mGoogleApiClient.connect();` inside `signOut()` method? `Auth.GoogleSignInApi.signOut(mGoogleApiClient);` was not enough? – Joan P. Jan 19 '18 at 15:43
  • 1
    @IoanaP. I can remember what the problem was exactly, but I think if you don't diconnect it won't ask to select account next time you try to sign in in the future. – Gonzalo Jan 19 '18 at 16:32
  • @Gonzalo I just tried without those lines and I was asked to select the account. So those lines are not necessary. Thanks, voted up anyway. – Joan P. Jan 20 '18 at 08:48
  • @IoanaP. I don't know, I meant I couldn't remember. May be if you try to sign just after sign out it won't ask. I should try again and see every situation. – Gonzalo Jan 20 '18 at 11:55
  • I've tried and if I sign-in just after sign out it's asking. – Joan P. Jan 20 '18 at 12:32
  • How to logout from different activity? If i am accessing from different activity it always shows that GoogleApiClient is not connected – Adit Kothari Mar 20 '18 at 09:13
  • What do you mean with diferent activity? This is to logout wherever you want. You must connect `onStart` to be able to disconnect – Gonzalo Mar 20 '18 at 10:41
5

I found this up-to-date solution:

if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
                        mGoogleApiClient.clearDefaultAccountAndReconnect().setResultCallback(new ResultCallback<Status>() {

                            @Override
                            public void onResult(Status status) {

                                mGoogleApiClient.disconnect();
                            }
                        });

                    }  

The usage of

Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);

is deprecated

https://developers.google.com/android/reference/com/google/android/gms/plus/Account

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

EDIT

THIS METHOD IS DEPRECATED

Use like this

 if (mGoogleApiClient != null)
            {
                if (mGoogleApiClient.isConnected())
                {
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);

                    mGoogleApiClient.disconnect();
                }
            }
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
Brendon
  • 1,368
  • 1
  • 12
  • 28
0

I've modified a code snippet from the android docs. This is a complete code snippet that logs in and out; displaying the user name, email and profile image. This code snippet is well tested. The origonal doc can be found here: https://developers.google.com/identity/sign-in/android/sign-in See this doc for dependencies.

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

    private ImageView imgUserAvatar;
    private TextView lblName;
    private TextView lblEmailID;
    private SignInButton btnSignIn;
    private Button btnSignOut;

    private GoogleSignInOptions gso;
    private GoogleSignInClient googleSignInClient;
    private GoogleSignInAccount account;
    private GoogleApiClient googleApiClient;

    private static final int RC_SIGN_IN = 58;

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

        imgUserAvatar = findViewById(R.id.imgUserAvatar);
        lblName = findViewById(R.id.lblName);
        lblEmailID = findViewById(R.id.lblEmailID);
        btnSignIn = findViewById(R.id.btnSignIn);
        btnSignOut = findViewById(R.id.btnSignOut);
        btnSignIn.setOnClickListener(this);
        btnSignOut.setOnClickListener(this);
        btnSignIn.setSize(SignInButton.SIZE_STANDARD);
        imgUserAvatar.setVisibility(View.GONE);
        lblName.setVisibility(View.GONE);
        lblEmailID.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.GONE);
        btnSignIn.setVisibility(View.VISIBLE);

        gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            //.requestIdToken(RT_GOOGLE_SIGN_ID_ID)
            .requestEmail()
            .build();
        googleSignInClient = GoogleSignIn.getClient(this, gso);
        googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
        account = GoogleSignIn.getLastSignedInAccount(this);
        updateUI(account);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()) {
            case R.id.btnSignIn:
                signIn();
                break;
            case R.id.btnSignOut:
                signOut();
                break;
        }
    }

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

    private void signOut() {

        Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
            @Override
            public void onResult(@NonNull Status status) {
                imgUserAvatar.setVisibility(View.GONE);
                lblName.setVisibility(View.GONE);
                lblEmailID.setVisibility(View.GONE);
                btnSignOut.setVisibility(View.GONE);
                btnSignIn.setVisibility(View.VISIBLE);
            }
        });
    }

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

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            //Signed in successfully, show authenticated UI.
            updateUI(account);
        }
        catch(ApiException e) {
            updateUI(null);
        }
    }

    private void updateUI(final GoogleSignInAccount account) {

        if(account != null) {
            lblName.setText(account.getDisplayName());
            lblEmailID.setText(account.getEmail());
            lblName.setVisibility(View.VISIBLE);
            lblEmailID.setVisibility(View.VISIBLE);
            btnSignOut.setVisibility(View.VISIBLE);
            btnSignIn.setVisibility(View.GONE);

            final Bitmap[] bitmap = new Bitmap[1];

            final Handler handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    imgUserAvatar.setImageBitmap(bitmap[0]);
                    imgUserAvatar.setVisibility(View.VISIBLE);
                    return true;
                }
            });

            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream in;
                    try {
                        in = new java.net.URL(account.getPhotoUrl().toString()).openStream();
                        bitmap[0] = BitmapFactory.decodeStream(in);
                        handler.sendEmptyMessage(0);
                    }
                    catch(IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        else if(account == null) {
            imgUserAvatar.setVisibility(View.GONE);
            lblName.setVisibility(View.GONE);
            lblEmailID.setVisibility(View.GONE);
            btnSignOut.setVisibility(View.GONE);
            btnSignIn.setVisibility(View.VISIBLE);
        }//End if(account != null)
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        //ToDo in context only used for signout.
    }
}

Also you may find this video useful: https://www.youtube.com/watch?v=2PIaGpJMCNs&t=

user2288580
  • 2,210
  • 23
  • 16