6

I met a problem in my project. I want to use "Google API" to log in in my LoginActivity. And Log out from another Activity(named WelcomeActivity)

LoginActivity: (code is here)

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

    // Configuration of Google API - Step 1/3
    private static final String TAG = "LoginActivity";
    private static final int RC_SIGN_IN = 9001;
    public static GoogleApiClient mGoogleApiClient;
    private ProgressDialog mProgressDialog;

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

    }
    public void GoogleAPI(){

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

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();

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

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

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

    // [START handleSignInResult]
    private void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            CustomApplication app = (CustomApplication)getApplication();
            GoogleSignInAccount acct = result.getSignInAccount();
            Intent i = new Intent(LoginActivity.this, WelcomePage.class);
            i.putExtra("Username", acct.getDisplayName());
            startActivity(i);
        }
    }
    // [END handleSignInResult]

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

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        ...
    }

    private void showProgressDialog() {
       ...
    }

    private void hideProgressDialog() {
       ...
    }

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

}

And I want to use Sign_out Method in my Welcome activity,

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

In order to solve this problem, i try 2 methods:

  1. make mGoogleApiClient as a global variable(extends Application or Singleton), i try it, but failed, in Welcome page, mGoogleApiClient is not null, but error is: mGoogleApiClient is not connected yet.

  2. i call LoginActivity.getMGoogleApiClient(static variable), but also failed, same error: mGoogleApiClient is not connected yet.

I already search this problem for days, but nothing useful to solve it, please help me ..

Leyla Lee
  • 466
  • 5
  • 19
  • Possible duplicate of [Access google plus client from multiple activities](http://stackoverflow.com/questions/16827839/access-google-plus-client-from-multiple-activities) – Iulian Nov 16 '15 at 22:32

2 Answers2

6

When you enableAutoManage, then the googleApiClient gets connected onStart and gets disconnected onStop and is handled automatically by the library. What you could is, logout the user in the other activity, whatever your code is to logout the user from your backend, except don't sign out from google yet.

Pseudo code:

private void logOut(){
    //your logout code in the log out activity

    setCurrentUser(null);
}

And in the activity with the googleApiClient, you could check if the user is logged-in in onConnected callback of googleApiClient. If the current user is not logged in, sign out the user from Google.

@Override
public void onConnected(Bundle connectionHint) {

    if (getCurrentUser() == null){
        signOut();
    }

}

private void signOut() {
    Auth.GoogleSignInApi.signOut(mGoogleApiClientPlus).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    //signed out.
                }
            });
}

If you don't use enableAutoManage and don't disconnect the client in onStop (which I don't know if it's recommended), you could use your 2 methods but I won't recommend using static fields for googleApiClient object.

Rahul Sainani
  • 3,437
  • 1
  • 34
  • 48
  • What you wrote is really good, it is the autoManage, you help me understand it. Thank you very much! – Leyla Lee Nov 23 '15 at 08:01
  • Glad it helped you. I was stuck with a similar problem myself. – Rahul Sainani Nov 23 '15 at 12:50
  • Hey, I have a doubt, if i use the autoManagement, mgoogleApiClient disconnect in which function? i try to do a test, but it is not in onDestory() or onStop() .. – Leyla Lee Nov 23 '15 at 17:13
  • 1
    Removing enableAutoManage() while creating mGoogleApiClient resolved my problem. – Shridutt Kothari Dec 11 '15 at 13:38
  • @droidster I'm using ur suggested method to do signout, but it would always appear the error 'GoogleApiClient is not connected yet' when I navigate to the other page and return to the signout page, can you help please? – Beeing Jk May 17 '16 at 09:34
  • @BeeingJk Are you using the same GoogleApiClient reference while signing out as the same which gets connected? If GoogleApiClient reference isn't connected, then it means you're not logged in. Seeing your code would help. – Rahul Sainani May 17 '16 at 14:57
1

One solution is to do your normal logout flow (ignore mGoogleApiClient). The next time the user opens your app to the login screen and hits google login, you log them out first, then do the google login

e.g.:

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

private void googleLogout() {
  if (mGoogleApiClient.isConnected()) {
    Auth.GoogleSignInApi.signOut(mGoogleApiClient);
  }
}
My House
  • 759
  • 2
  • 6
  • 18