简体   繁体   English

如何以编程方式从Facebook SDK 3.0注销而不使用Facebook登录/注销按钮?

[英]How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

The title says it all. 标题说明了一切。 I'm using a custom button to fetch the user's facebook information (for "sign up" purposes). 我正在使用自定义按钮来获取用户的Facebook信息(用于“注册”目的)。 Yet, I don't want the app to remember the last registered user, neither the currently logged in person via the Facebook native app. 然而,我不希望应用程序记住最后一个注册用户,也不想通过Facebook本机应用程序当前登录的用户。 I want the Facebook login activity to pop up each time. 我希望每次都能弹出Facebook登录活动。 That is why I want to log out any previous users programmatically. 这就是为什么我想以编程方式注销任何以前的用户。

How can I do that? 我怎样才能做到这一点? This is how I do the login: 这是我登录的方式:

private void signInWithFacebook() {

    SessionTracker sessionTracker = new SessionTracker(getBaseContext(), new StatusCallback() 
    {
        @Override
        public void call(Session session, SessionState state, Exception exception) { 
        }
    }, null, false);

    String applicationId = Utility.getMetadataApplicationId(getBaseContext());
    mCurrentSession = sessionTracker.getSession();

    if (mCurrentSession == null || mCurrentSession.getState().isClosed()) {
        sessionTracker.setSession(null);
        Session session = new Session.Builder(getBaseContext()).setApplicationId(applicationId).build();
        Session.setActiveSession(session);
        mCurrentSession = session;
    }

    if (!mCurrentSession.isOpened()) {
        Session.OpenRequest openRequest = null;
        openRequest = new Session.OpenRequest(RegisterActivity.this);

        if (openRequest != null) {
            openRequest.setPermissions(null);
            openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);

            mCurrentSession.openForRead(openRequest);
        }
    }else {
        Request.executeMeRequestAsync(mCurrentSession, new Request.GraphUserCallback() {
              @Override
              public void onCompleted(GraphUser user, Response response) {
                  fillProfileWithFacebook( user );
              }
            });
    }
}

Ideally, I would make a call at the beginning of this method to log out any previous users. 理想情况下,我会在此方法的开头调用以注销任何以前的用户。

Update for latest SDK: 最新SDK的更新:

Now @zeuter's answer is correct for Facebook SDK v4.7+: 现在@ zeuter的答案对于Facebook SDK v4.7 +是正确的:

LoginManager.getInstance().logOut();

Original answer: 原始答案:

Please do not use SessionTracker. 请不要使用SessionTracker。 It is an internal (package private) class, and is not meant to be consumed as part of the public API. 它是一个内部(包私有)类,并不打算作为公共API的一部分使用。 As such, its API may change at any time without any backwards compatibility guarantees. 因此,其API可能随时更改,无任何向后兼容性保证。 You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead. 您应该能够在代码中删除SessionTracker的所有实例,而只需使用活动会话。

To answer your question, if you don't want to keep any session data, simply call closeAndClearTokenInformation when your app closes. 要回答您的问题,如果您不想保留任何会话数据,只需在应用关闭时调用closeAndClearTokenInformation即可。

This method will help you to logout from facebook programmatically in android 此方法将帮助您在android中以编程方式从facebook注销

/**
 * Logout 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

    }

}

自Facebook的Android SDK v4.0(请参阅changelog )以来,您需要执行以下操作:

LoginManager.getInstance().logOut();

Here is snippet that allowed me to log out programmatically from facebook. 这是允许我从facebook以编程方式注销的片段。 Let me know if you see anything that I might need to improve. 如果您发现我可能需要改进的任何内容,请告诉我。

private void logout(){
    // clear any user information
    mApp.clearUserPrefs();
    // find the active session which can only be facebook in my app
    Session session = Session.getActiveSession();
    // run the closeAndClearTokenInformation which does the following
    // DOCS : Closes the local in-memory Session object and clears any persistent 
    // cache related to the Session.
    session.closeAndClearTokenInformation();
    // return the user to the login screen
    startActivity(new Intent(getApplicationContext(), LoginActivity.class));
    // make sure the user can not access the page after he/she is logged out
    // clear the activity stack
    finish();
}

Since Facebook's Android SDK v4.0 you need to execute the following: 自Facebook的Android SDK v4.0起,您需要执行以下操作:

LoginManager.getInstance().logOut();

This is not sufficient. 这还不够。 This will simply clear cached access token and profile so that AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile() will now become null. 这将简单地清除缓存的访问令牌和配置文件,以便AccessToken.getCurrentAccessToken()Profile.getCurrentProfile()现在将变为null。

To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut(); 要完全注销,您需要撤消权限,然后调用LoginManager.getInstance().logOut(); . To revoke permission execute following graph API - 要撤消权限,请执行以下图API -

    GraphRequest delPermRequest = new GraphRequest(AccessToken.getCurrentAccessToken(), "/{user-id}/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse graphResponse) {
            if(graphResponse!=null){
                FacebookRequestError error =graphResponse.getError();
                if(error!=null){
                    Log.e(TAG, error.toString());
                }else {
                    finish();
                }
            }
        }
    });
    Log.d(TAG,"Executing revoke permissions with graph path" + delPermRequest.getGraphPath());
    delPermRequest.executeAsync();

Session class has been removed on SDK 4.0. SDK 4.0上已删除会话类。 The login magement is done through the class LoginManager . 登录magement通过类LoginManager完成 So: 所以:

mLoginManager = LoginManager.getInstance();
mLoginManager.logOut();

As the reference Upgrading to SDK 4.0 says: 作为参考升级到SDK 4.0说:

Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class. 会话已删除 - AccessToken,LoginManager和CallbackManager类取代并替换Session类中的功能。

Yup, As @luizfelippe mentioned Session class has been removed since SDK 4.0. 是的,因为@luizfelippe提到自SDK 4.0以来已经删除了Session We need to use LoginManager. 我们需要使用LoginManager。

I just looked into LoginButton class for logout. 我只是查看了LoginButton类的logout。 They are making this kind of check. 他们正在进行这种检查。 They logs out only if accessToken is not null. 仅当accessToken不为null时,它们才会注销 So, I think its better to have this in our code too.. 所以,我认为在我们的代码中也有这个更好..

AccessToken accessToken = AccessToken.getCurrentAccessToken();
if(accessToken != null){
    LoginManager.getInstance().logOut();
}
private Session.StatusCallback statusCallback = new SessionStatusCallback();

logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Session.openActiveSession(this, true, statusCallback);  
}
});

private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
session.closeAndClearTokenInformation();    
}
}

Facebook provides two ways to login and logout from an account. Facebook提供了两种从帐户登录和注销的方法。 One is to use LoginButton and the other is to use LoginManager. 一种是使用LoginButton,另一种是使用LoginManager。 LoginButton is just a button which on clicked, the logging in is accomplished. LoginButton只是一个按钮,单击该按钮即可完成登录。 On the other side LoginManager does this on its own. 另一方面,LoginManager自行完成此操作。 In your case you have use LoginManager to logout automatically. 在您的情况下,您已使用LoginManager自动注销。

LoginManager.getInstance().logout() does this work for you. LoginManager.getInstance().logout()这对你LoginManager.getInstance().logout()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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