Sign out from google and facebook in android application

我的未来我决定 提交于 2019-12-09 04:13:43

问题


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.


回答1:


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



回答2:


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




回答3:


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



回答4:


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



回答5:


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




回答6:


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.




回答7:


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.




回答8:


For google account

Auth.GoogleSignInApi.signOut(mGoogleApiClient);

and for facebook account

LoginManager.getInstance().logOut();



回答9:


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)




回答10:


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) {

        }
    }



回答11:


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


来源:https://stackoverflow.com/questions/27921515/sign-out-from-google-and-facebook-in-android-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!