Facebook SDK 4 for Android - how to log out programmatically

Recently, Facebook released SDK 4 with new and cool updates. I tried to switch into SDK4 to use new features, however, I am struggling with the Login feature of Facebook.

So far, to log out Facebook programmatically, I used :

Session session = Session.getActiveSession();
session.closeAndClearTokenInformation();

But SDK4 seems not to support Session anymore, and in official docs, they mention:

There are two ways to implement Facebook login on Android:

LoginButton class - Which provides a button you can add to your UI. It follows the current access token and can log people in and out.

Well, seems there's no way to log out Facebook programmatically except using LoginButton. Anyone have any idea, please share it here.

95698 次浏览

即使使用 LoginButton,也可以使用 LoginManager.getInstance().logOut();,因为

此 UI 元素包装 LoginManager 中可用的功能。

编辑: 顺便说一下,这对 Facebook SDK v4是有效的。我不知道他们将来是否会改变它。

@ batoutofhell 提到,不要忘记使用 FacebookSdk.sdkInitialize(getApplicationContext());初始化 facebook sdk。详情请参阅 给你

使用 loginButton 处理:

//Check if user is currently logged in
if (AccessToken.getCurrentAccessToken() != null && com.facebook.Profile.getCurrentProfile() != null){
//Logged in so show the login button
fbLogin.setVisibility(View.VISIBLE);
fbLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//log out
LoginManager.getInstance().logOut();
gotoLogin();
}
});
}

SDK4,如果你想完全脱钩,确保你也从用户的 facebook 帐户删除应用程序。此方法完全断开用户的连接:

public void disconnectFromFacebook() {


if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}


new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {


LoginManager.getInstance().logOut();


}
}).executeAsync();
}

您可以使用 LoginManager 注销,但也必须使用图形请求。我说的是完全注销,这样,下次你可以用不同的帐户登录。

new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
@Override
public void onCompleted(GraphResponse graphResponse) {


SharedPreferences pref = DashBoard.this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
LoginManager.getInstance().logOut();


Intent logoutint = new Intent(DashBoard.this,MainActivity.class);
logoutint.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(logoutint);


}
}).executeAsync();

通过共享首选项的帮助,您可以完全注销,下次您可以用不同的帐户登录。

Frank version kotlin:

 fun disconnectFromFacebook() {
if (AccessToken.getCurrentAccessToken() == null) {
return  // already logged out
}
GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/permissions/",
null,
HttpMethod.DELETE,
GraphRequest.Callback {
LoginManager.getInstance().logOut()
}).executeAsync()
}