简体   繁体   中英

Sign out from google and facebook in android application

I have integrated google and facebook sign up using their respective methods. But after successful signing, I want to open different activity and similarly user can go to various different activities. I have used action bar where I am giving an option to sign out from either of the account that the user has logged in. How could I sign out the user when I am in different activity then the main activity. I am getting an exception and I am not able to pass apiclient reference (for google) and session reference (for facebook) to another activity. Please help. Thanks in advance.

Log out from google:

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 you can set setOnClickListener on button:

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

For Facebook

LoginManager.getInstance().logOut();

For Google

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

            GoogleSignInClient googleSignInClient=GoogleSignIn.getClient(context,gso);
            googleSignInClient.signOut();

Log out from facebook:

public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {

    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
        //clear your preferences if saved
    }
} else  {

    session = new Session(context);
    Session.setActiveSession(session);

    session.closeAndClearTokenInformation();
        //clear your preferences if saved

 }

}

Log out from google:

@Override
public void onClick(View view) {
if (view.getId() == R.id.sign_out_button) {
if (mGoogleApiClient.isConnected()) {
  Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
  mGoogleApiClient.disconnect();
  mGoogleApiClient.connect();
  }
 }
}

guide's docs

Updated from 7 Nov 2017 Latest Code For Login and Logout Event

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .build();
    GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

Google Logout

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

Google RevokeAccess

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

Refer Google Code Here

Facebook Logout

LoginManager.getInstance().logOut();

Refer Facebook Doc Here

just add on your new activity this:

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

and then

@Override
    public void onClick(View v)  {
            switch (v.getId()) {
                case R.id.sign_out_button2:

                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.disconnect();
                        mGoogleApiClient.connect();

logout from facebook is pretty easy

just add the following code

LoginManager.getInstance().logOut();

you can then redirect the user to login activity by adding following code further

LoginManager.getInstance().logOut();
Intent intent = new Intent(CurrentActivity.this, LoginActivity.class);
startActivity(intent);
finish();

so your final code for logoutFromFacebook would be

public void logoutFromFacebook(){
    LoginManager.getInstance().logOut();
    Intent intent = new Intent(CurrentActivity.this, LoginActivity.class);
    startActivity(intent);
    finish();
}

Now just call that method on your logout button event.

Firstly for Facebook logout :

LoginManager.getInstance().logOut();

If you are trying to logout from other activity or fragment this will gives you error like Facebook sdk not initialised. Then firstly you have to initialise facebook sdk like :

FacebookSdk.sdkInitialize(your context here);

and then logout from manager.

Secondary for google logout :

first you have to check that google client is connected or not and if connected then call for logout code:

if (mGoogleApiClient.isConnected())
   Auth.GoogleSignInApi.signOut(mGoogleApiClient);

here mGoogleApiClient is object of GoogleApiClient.

For google account

Auth.GoogleSignInApi.signOut(mGoogleApiClient);

and for facebook account

LoginManager.getInstance().logOut();

For Logout from Facebook.

public void logoutFromFacebook() {
        Session session = Session.getActiveSession();
        session.closeAndClearTokenInformation();
        // Clear Preferences and other data and go back to login activty
    }

For logout from Google+. Keep in mind that Google+ logout is a bit trickier than that of Facebook. You will have to manage a boolean to keep track of events when logout is clicked (same as you did with login).

public void logoutFromGooglePlus() {
        mGooglePlusLogoutClicked = true;  // Keep track when you click logout
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            revokeAccess();
        } else {
            mGoogleApiClient.connect();   // It can send user to onConnected(), call logout again from there
        }
    }

// revoke access (if needed)
protected void revokeAccess() {

        Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        mGoogleApiClient.disconnect();
                        mGoogleApiClient.connect();
                        // Clear data and go to login activity
                    }
                });
    }

To answer the question in comment: GoogleApiClient can be instantiated many times in an application and it still takes the same instance as it was initialized first time. So don't worry about how to "pass" GoogleApiClient among activities. It is a lightweight client designed to be initialized as a new instance in each activity. Just build a new GoogleAPiClient , call .connect() and start working. However, you will have to implement the interfaces needed for it, but you can leave the methods empty if you don't intend to do any work there.

As far as mLogoutClicked boolean is concerned, you can have your own implementation as you wish. Basically it's just a way to tell the onConnected() method that you came for a logout. (look at code, we are calling .connect() on logout too. So it might go into onConnected() and clash with your login code). You would do something like this on your onconnected()

public void onConnected(Bundle connectionHint) {

        if (mGooglePlusLogoutClicked) {
            logoutFromGooglePlus();
            mGooglePlusLogoutClicked = false;
        }
    }

As an advice on your flow of implementation, have a base class do all the GoogleApiClient initializing and let Login activity and other activities extend it. So it will implicitly handle the problem of initializing a client in each activity. Just implement common onConnected() , onConnectionFailed() etc code in base activity and let login activity override these to implement login logic. (and same for logout activity. It will override these and handle logout code)

public class LogOutActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
        GoogleApiClient mGoogleApiClient;
        Button btnLogout;

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

            btnLogut = (Button) findViewBy(R.id.btnLogout);

            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();


            btnLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(@NonNull Status status) {
                        }

                        Intent intent = new Intent(mContext, LoginActivity.class);
                    });
                }
            });
        }

        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        }
    }

Just this also in another activity different from the Login one where do you should have the Login button.

GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(fromActivity.getString(R.string.default_web_client_id))
            .requestEmail()
            .requestProfile()
            .build();
    // Build a GoogleSignInClient with the options specified by gso.
    GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(fromActivity, gso);
    mGoogleSignInClient.signOut();

注销 Google 身份验证的最简单方法:

GoogleSignIn.getClient(getApplicationContext(), GoogleSignInOptions.DEFAULT_SIGN_IN).signOut();

Here you go For Google.

 Button login, signup, signout;
    GoogleSignInClient mGoogleSignInClient;
    private static final int RC_SIGN_IN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        login = findViewById(R.id.login);
        signup = findViewById(R.id.signup);
        signout = findViewById(R.id.signout);
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        signout.setOnClickListener(v -> mGoogleSignInClient.signOut()
                .addOnCompleteListener(this, task -> Log.e("checker", "Sign Out")));
        signup.setOnClickListener(v -> {
            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, RC_SIGN_IN);
        });

        login.setOnClickListener(v -> {
            GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
            if (account != null) {
                String personName = account.getDisplayName();
                String personEmail = account.getEmail();
                String personId = account.getId();
                Uri personPhoto = account.getPhotoUrl();
                Log.e("checker", personName);
                Log.e("checker", personId);
                Log.e("checker", String.valueOf(personPhoto));
                Log.e("checker", personEmail);
            } else
                Log.e("checker", "did not login");
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
        try {
            GoogleSignInAccount account = completedTask.getResult(ApiException.class);
            if (account != null) {
                String personName = account.getDisplayName();
                String personEmail = account.getEmail();
                String personId = account.getId();
                Uri personPhoto = account.getPhotoUrl();
                Log.e("checker", personName);
                Log.e("checker", personId);
                Log.e("checker", String.valueOf(personPhoto));
                Log.e("checker", personEmail);
            }
            else
                Log.e("checker", "Failed!");
        } catch (ApiException e) {
            Log.e("checker", "signInResult:failed code=" + e.getStatusCode());

        }
    }

This is for Facebook.

LoginManager.getInstance().logOut();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM