I'm updating an app that use facebook sdk, but i'm facing some problems, and official documentation is too poor.
On my app, user can log in with facebook or with a normal account (stored on my server), and this options are showed on app startup. Obviously user can also log out and log in with another account (facebook or not), and i have a problem with facebook logout. In fact i'm not able to logout user connected with facebook account.
As i've noticed after a lot of attempts, all changes about facebook status are tracked by AccessTokenTracker and ProfileTracker, that should be instantiated only once at startup.
I show (and explain) my code.
This is code of my login FragmentActivity that check if user was already logged in (with facebook or with dedicated account), and if yes, show next activity, else show fragment for choose access options:
#Override
protected void onCreate(Bundle savedInstanceState) {
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
if (currentAccessToken != null) {
Log.i("LOGINACTIVITY", "token tracker, current token valid");
AccessToken token = AccessToken.getCurrentAccessToken();
//already logged with facebook, show next activity
} else {
//check if current visible activity is logout activity
// that contains logout button
ActivityManager am = (ActivityManager) LoginActivity.this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
String top_activity = taskInfo.get(0).topActivity.getClassName();
if (top_activity.equals(getApplicationContext().getPackageName() + ".LogoutActivity")) {
//launch new login activity
LoginManager.getInstance().logOut();
getApplicationContext().startActivity(new Intent(getApplicationContext(),
LoginActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
}
}
};
accessTokenTracker.startTracking();
Now it happen that, when i press logout button, accesstoken tracker execute else branch so show login options it's showed, but for some reason app automatically login again with facebook (it's invoked if branch of TokenTracker), so user is not able to logout from facebook.
What's wrong?
Make sure to stop access token tracker before logging out to avoid getting onCurrentAccessTokenChanged(...) called with a null currentAccessToken, which will cause - According to your code - to execute else clause.
accessTokenTracker.stopTracking();
LoginManager.getInstance().logOut();
And BTW, you don't have to use startTracking() right after executing new AccessTokenTracker(), as AccessTokenTracker() implements startTracking()
AccessTokenTracker.class
public AccessTokenTracker() {
Validate.sdkInitialized();
this.receiver = new AccessTokenTracker.CurrentAccessTokenBroadcastReceiver();
this.broadcastManager = LocalBroadcastManager.getInstance(FacebookSdk.getApplicationContext());
this.startTracking();
}
Related
i´m not able to find any solution that solves my Problem.
I use Firebase and Facebook to sign up to my app.
When I first sign up to my app, i get the following screen:
Facebook First Login-Screen
I sign out from Firebase and Facebook using the following Lines of Code:
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
When I´m trying after that to sign in with Facebook again, I get the following Screen:
Facebook Second Login-Screen
I´m only able to continue with the Account I used before.
I want to come back to the first Screen, where I have to enter E-Mail an Password so I could Sign in with another Facebook Account if I want.
On Stackoverflow I found the following promising Code:
FacebookSdk.sdkInitialize(getApplicationContext());
if (AccessToken.getCurrentAccessToken() != null) {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logOut();
}
}).executeAsync();
}
But this solved also not my Problem.
After that I get the following Screen:
Facebook alternate Second Login-Screen
I would by very thankful for any help and sorry for any English mistakes.
Use below code before you click on facebook login button
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
accessTokenTracker.stopTracking();
DebugLog.infoLog("Token Changed Called");
if (currentAccessToken == null) {
LoginManager.getInstance().logInWithReadPermissions(mActivity, Arrays.asList(permissionList));;
}
}
};
AccessToken.refreshCurrentAccessTokenAsync();
After above code just call login code as mentioned below (use handler to call below code with 1 milliseconds wait time):
LoginManager.getInstance().logInWithReadPermissions(mActivity, Arrays.asList(permissionList));
I am implementing a Facebook login with Facebook SDK on Android.
compile 'com.facebook.android:facebook-android-sdk:4.+'
I'm logging in with the user as
callbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
..
}
And for log out, I use my own log out button and log out the user programmatically:
LoginManager.getInstance().logOut();
My question is:
After log out, when I click on Continue with Facebook, the previous user information pops up to Continue as XY. I don't want this. I want to ask for email and password again, every time, if somebody wants to log in after log out. How can I do this?
Actually i found the solution. I changed the login behavior for the FB login button, for this i used:
loginButton.setLoginBehavior(LoginBehavior.WEB_ONLY);
So every time it pops up the WEB view for login button.
I want to ask for email, password again every time if somebody wants
to log in after log out.
try this in your onCreate()
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
updateWithToken(AccessToken.getCurrentAccessToken()); //add this method
Now in updateWithToken() method logout the user from previous session
private void updateWithToken(AccessToken currentAccessToken) {
if (currentAccessToken != null) {
LoginManager.getInstance().logOut();
} else {
}
}
EDIT
if you want to completely disconnect user from facebook login use:
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();
}
To really disconnect from facebook with the android SDk and avoid auto login after you must use
val accessToken = AccessToken.getCurrentAccessToken()
val request = GraphRequest.newDeleteObjectRequest(accessToken, "me/permissions", { response ->
LoginManager.getInstance().logOut() //not really needed i think
})
request.executeAsync()
In response you have a responseCode == 200 if OK
My problem is the following: I notice that some users trying to login in my app fail to login. It happens to maybe 20% of them and I am not sure which phone they use. I notice the observation on iPhone and android phones.
I believe this is maybe due to one of my parameter in the facebook console, but I am not sure which one.
Did anyone of you entered in that scenario before?
At the moment I can see the API stat from facebook that see errors when users try to login but I do not know how to get the error information
At the moment it looks like those users always end up in the error case of the facebook API when logging in.
Objective C code:
if([FBSDKAccessToken currentAccessToken] != nil)
[self loginUser];
else{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorSystemAccount;
// THIS PART ALWAYS SWAP FROM MY APP TO FACEBOOK APP
[login logInWithReadPermissions:#[FACEBOOK_EMAIL, FACEBOOK_PUBLICPROFILE] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error){
[login logOut];
}
else if ([result isCancelled] == YES){
[login logOut];
}
else{
[self loginUser];
}
}];
}
Android code:
FacebookSdk.sdkInitialize(getApplicationContext());
LoginManager loginManager = LoginManager.getInstance();
callbackManager = CallbackManager.Factory.create();
// Register the callback manager to the facebook login manager
loginManager.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
// If the callback is sucessfull then we log the user in
public void onSuccess(LoginResult loginResult) {
logUserIntoApp();
}
#Override
// If the callback specify that the user cancel the facebook login
public void onCancel() {
Mint.logExceptionMessage("onCancelFacebookLogin", null, new Exception("onCancelFacebookLogin"));
setFinResult(CANCEL);
}
#Override
// If there was an error, we specify that there was an error during the facebook login
public void onError(FacebookException exception){
Mint.logExceptionMessage("onErrorFacebookLogin", null, new Exception("onErrorFacebookLogin"));
setFinResult(FAIL);
}
});
// First check if the user is already logged in, and if he is then logged in automatically in TMO
if (isLogedIn()) logUserIntoApp();
// Otherwise login the user with the required permissions
else loginManager.logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "user_birthday", "public_profile"));
Here are the store links too:
https://play.google.com/store/apps/details?id=pro.appus.takemeout
https://itunes.apple.com/gb/app/tmo-dating/id1032349052?mt=8
Any help on this would be very appreciated. thanks
I have an Android application that uses Facebook sdk to log in. To do so, I use the LoginButton widget. The log in process works very well but I got a small problem : when I close the application or reinstall it, it automatically logs in into Facebook (the text on button switches to "Log out"). I don't want to have such behavior : I need that the user clicks on the button to log in every time the application starts. I checked on the internet and it seems this feature is called "single sign on" but I'm not sure about that. I have found several ways to do so but none of them works. I used Facebook SDK 4. This is the part of the code that instantiates the Activity.
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
this.setContentView(R.layout.login_layout);
getSupportActionBar().hide();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).build();
mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
/*accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
updateWithToken(newAccessToken);
}
};*/
LoginManager.getInstance().logInWithReadPermissions(LogInActivity.this, Arrays.asList("public_profile", "user_birthday", "email"));
LoginManager.getInstance().setLoginBehavior(LoginBehavior.SUPPRESS_SSO);
fb_login = ((LoginButton) findViewById(R.id.fb_login));
fb_login.setLoginBehavior(LoginBehavior.SUPPRESS_SSO);
fb_login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.i("Facebook connect", "Connection success");
}
#Override
public void onCancel() {
Log.i("Facebook", "Super c'et cancel");
((TextView) findViewById(R.id.account)).setText("Annulé");
}
#Override
public void onError(FacebookException error) {
Log.i("Facebook", "Super y a une erreur");
((TextView) findViewById(R.id.account)).setText("Erreur");
}
});
Does someone have an idea how to disable to automatic connection ?
For Facebook SDK 4 and onwards, you could programmatically logout using:
LoginManager.getInstance().logOut();
Now, the problem is where do you place this code. If you're fine with Facebook logout when the app is sent to the background, you can use onPause() or onStop() methods.
The big part comes. You can't determine if the app is killed. Because it's simply killed and you don't get any callbacks to catch that event.
So, if you anyway want to implement this every-time-login thing, you have to do this when the app starts.
Initialize the Facebook SDK:
Check if the user is logged in.
If yes in step 2, run manual logout.
FacebookSdk.sdkInitialize(getApplicationContext());
if(AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
step 1: like was written before you should make
LoginManager.getInstance().logOut();
step 2: To remove autologin just avoid behavior of Facebook app. You could do it via LoginBehavior.
LoginManager.getInstance().setLoginBehavior(LoginBehavior.WEB_ONLY);
Remove this line from your code
LoginManager.getInstance().logInWithReadPermissions(LogInActivity.this, Arrays.asList("public_profile", "user_birthday", "email"));
I post here because I've got a problem.
I'm working on a new android application , and I want to know how I can detect when a user is disconnecting (facebook logout button), because I want to refresh my UI at this moment.
I have been watched the official documentation, but I found nothing.
You can set a listener on the onCreate() method on your activity
AccessTokenTracker accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null){
//User logged out
}
}
};
You need to import com.facebook.AccessToken and com.facebook.AccessTokenTracker
When you create the instance of AccessTokenTracker it implicitly starts tracking. For stopping tracking you should call AccessTokenTracker.stopTracking() e.g. in onDestroy() to not receive anymore events when not needed/wanted and especially to not leak memory!
You can get any time if the user is logged in/out by calling
AccessToken at = AccessToken.getCurrentAccessToken();
If the user is not logged in, you get a null value.
For further reference please check the documentation at https://developers.facebook.com/docs/reference/android/current/class/AccessTokenTracker/
You can try this also
if(AccessToken.getCurrentAccessToken()!=null)
{
Log.v("User is login","YES");
}
else
{
Log.v("User is not login","OK");
LoginManager.getInstance().logInWithReadPermissions(WelcomeActivity1.this, (Arrays.asList("public_profile", "user_friends","user_birthday","user_about_me","email")));
}