Reputation: 93
I am building an Android application where I am using Facebook login, and after Facebook login, I get access_token and session that are stored in shared preferences in private mode.
I am using the Facebook login code below in an activity and I want the user to logout from Facebook from another fragment. How do I code on the fragment so that my current logged-in account logs out from Facebook?
Here is my Facebook login code:
/**
* Function to login into facebook
*/
@SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
// call getprofileinformation function to get user details
getProfileInformation();
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[]{"email", "publish_stream"},
new Facebook.DialogListener() {
@Override
public void onCancel() {
// Function to handle cancel event
}
@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
// call getprofileinformation function to get user
// details
getProfileInformation();
}
@Override
public void onError(DialogError error) {
// Function to handle error
}
@Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
Upvotes: 0
Views: 500
Reputation: 12358
Call this closeAndClearTokenInformation method to logout from facbook. This method closes the local in-memory Session object and clears any persisted token cache related to the Session.
Upvotes: 0
Reputation: 655
Try this :
private static void LogoutFB(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
}
}
Upvotes: 0