Logout in Facebook Using android fb SDK 3.0 - android

my app using android facebook sdk 3.0,after login getting some response,after that i need to signout from facebook clicking on button.
How to log-out from the session in facebook
pls help

You should do something like this.
if (Session.getActiveSession() != null) {
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
Also if you store the user token in some other way you should clear that too.

This method will help you to logout from facebook programmatically in android
/**
* 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
}
}

Related

FACEBOOK Re-Login Not work Properly

When I Login First Time with Facebook it work Properly and Redirect To another Page,but when I perform sign out operation with Facebook Account And Re-login With Facebook It can Not work Properly till Relaunch application.
If I Relaunch Application it perform Login properly.
This method will help you to clear token information and 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
}
}

Android Facebook SDK 3 - request new permission but can't reauthorized

I have some problem with my code, i've followed hellofacebook example to post photo. But when i try to make new permission "publish_action", the code doesn't callback anything. Here is my code
private void performPublish(PendingAction action, boolean allowNoSession){
Session session = Session.getActiveSession();
if(session != null){
Toast.makeText(getApplicationContext(),"enter session unnull",Toast.LENGTH_SHORT).show();
pendingAction = action;
if(hasPublishPermission()){
Toast.makeText(getApplicationContext(),"enter haspublish",Toast.LENGTH_SHORT).show();
handlePendingAction();
Toast.makeText(getApplicationContext(),"Posted Success",Toast.LENGTH_SHORT).show();
return;
} else if(session.isOpened()) {
Toast.makeText(getApplicationContext(),"enter session opened",Toast.LENGTH_SHORT).show();
Session.NewPermissionsRequest newPermission = new Session.NewPermissionsRequest(Third.this,PERMISSION);
session.requestNewPublishPermissions(newPermission);
Toast.makeText(getApplicationContext(),"Posted Failed",Toast.LENGTH_SHORT).show();
return;
}
if(allowNoSession) {
pendingAction = action;
handlePendingAction();
}
}
}
Please help me if you can, because i'm newbie with facebook SDK. Thank you
according to new facebook sdk, you need to submit your app for review if you are publishing anything. after facebook approval you can upload picture by using any login. you can check this link for review process
https://developers.facebook.com/docs/apps/review/
https://github.com/sauce/guide/wiki/Facebook's-approval-process

Android Facebook SDK Remember Session

I'm writing an application which requires facebook login. I can make user log in when he/she first opens the application. However, I can't retrieve the session after they restart the application. My login code is the following:
private static Session openActiveSession(Activity activity, boolean allowLoginUI, StatusCallback callback, List<String> permissions) {
OpenRequest openRequest = new OpenRequest(activity).setPermissions(permissions).setCallback(callback);
Session session = new Session.Builder(activity).build();
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState()) || allowLoginUI) {
Session.setActiveSession(session);
session.openForRead(openRequest);
return session;
}
return null;
}
And I use isLoggedIn method when the app is opened in order to understand if the user is logged in or not.
public static boolean isLoggedIn() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
return true;
} else {
return false;
}
}
But when the application is closed and reopened, this method never returns true.
How can I retrieve old session back without showing a popup window to want user's facebook account informations, if he/she logged in in the past.
You can call Session.openActiveSessionFromCache which will open the active session only if there's a cached access token, or return null otherwise.

Android facebook sdk 3.0.1 using last session

I have the following scenario with facebook sdk 3.0.1. When user first login and chooses "FB login" then the SSO starts, a new session is open and everything works fine. But then, when the user closes the app and start it again - I don't understand how to get the last open session, currently I'm opening a new session and the user sees again the FB progress bar(while it's being connected to FB again, even so the user already approved FB in his last run). Does anybody know how to skip this operation?
Edit 1:
This is how I retrieve the session:
public void tryRetrievFacebookSession() {
Session session = Session.getActiveSession();
if (session != null && session.isOpened())
return;
session = Session.openActiveSession(this, true, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
MobliLog.d("SplashScreen", "Inside call() with session with state: " + session.getState());
// onSessionStateChanged(session, state, exception);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session session = Session.getActiveSession();
if (session != null)
session.onActivityResult(this, requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
The session is normally being created or from the LoginButton or with those lines:
session = Session.getActiveSession();
if (session.getState().isClosed())
session = new Session(this);
if (session.isOpened()) {
onAuthenticationEndListener.onSuccessfullAuthentication();
return;
} else {
this.onFacebookAuthenticationEndListener = onAuthenticationEndListener;
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(SocNetwksCompatScreen.this).setCallback(null));
return;
}
Information 1:
When I'm doing the first Session session = Session.getActiveSession(); in the logins after the sso authentication, my session has state CLOSED instead of OPENED
Information 2:
I'm using uiHelper and initialize it like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
twitter = SocialPluginsUtils.getTwitterClient();
uiHelper = new UiLifecycleHelper(this, statusCallback);
uiHelper.onCreate(savedInstanceState);
}
Now, I know that after I perform Session.getActiveSession(); the session state should get OPENED and after that OPEN and then the uiHelper's callback should be invoked. In my code the state is CLOSED or CLOSED_LOGIN_FAILED or CREATED(not sure why it's not stable) and the rest doesn't happens
In fact the sessions are being closed every time the user closed the app.
So if Session.getActiveSession() return a null session you only need to call Session.openActiveSession(activity, true, sessionCallback).
If there is a valid token cache this method will use it in order to open a new session without the need for the user to insert any data. Otherwise this will shows the default dialog with the basic permissions.
From what I can see after your edit maybe the problem is related with the way in which you manage the session.
I use this code in my projects:
Session session = Session.getActiveSession();
if (session == null){
Session.openActiveSession(activity, true, sessionCallback);
}
else if (!session.getState().isOpened()){
session.openForRead(new Session.OpenRequest(activity)
.setCallback(sessionCallback));
//this will open the session with basic read permissions
}
else {
//do what you want with the opened session
}
Moreover if you use the UiLifecycleHelper you don't need the two line of code that I suggest to you in the comment, they are already in the method of the helper. But you must be sure to call all the methods of the helper in each related method of the activity (onResume, onPause etc.)
If there isn't a token cache the openActiveSession(activity, true, sessionCallback) will automatically call a new dialog and if the user login with success a new token cache will be available for future uses.
Problem solved. I accidentally called session.closeAndClearTokenInformation(); in the onStop() (yeah, so stupid!)

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). Yet, I don't want the app to remember the last registered user, neither the currently logged in person via the Facebook native app. I want the Facebook login activity to pop up each time. 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:
Now #zeuter's answer is correct for Facebook SDK v4.7+:
LoginManager.getInstance().logOut();
Original answer:
Please do not use SessionTracker. It is an internal (package private) class, and is not meant to be consumed as part of the public API. As such, its API may change at any time without any backwards compatibility guarantees. You should be able to get rid of all instances of SessionTracker in your code, and just use the active session instead.
To answer your question, if you don't want to keep any session data, simply call closeAndClearTokenInformation when your app closes.
This method will help you to logout from facebook programmatically in android
/**
* 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
}
}
Since Facebook's Android SDK v4.0 (see changelog) you need to execute the following:
LoginManager.getInstance().logOut();
Here is snippet that allowed me to log out programmatically from 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:
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.
To completely logout you need to revoke permissions and then call LoginManager.getInstance().logOut();. To revoke permission execute following graph 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. The login magement is done through the class LoginManager. So:
mLoginManager = LoginManager.getInstance();
mLoginManager.logOut();
As the reference Upgrading to SDK 4.0 says:
Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class.
Yup, As #luizfelippe mentioned Session class has been removed since SDK 4.0. We need to use LoginManager.
I just looked into LoginButton class for logout. They are making this kind of check. They logs out only if accessToken is not 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. One is to use LoginButton and the other is to use LoginManager. LoginButton is just a button which on clicked, the logging in is accomplished. On the other side LoginManager does this on its own. In your case you have use LoginManager to logout automatically.
LoginManager.getInstance().logout() does this work for you.

Categories

Resources