How to detect logout event with the Facebook Android API v4? - android

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")));
}

Related

How can the Dropbox API alert when a token is received?

I am able to log in and do export/import from my Android app using the v2 Dropbox API. The only problem is on first run when a token is requested and the Dropbox app/website is launched - I have to run Auth.startOAuth2Authentication at least twice with a pause in between to be able to read the token with Auth.getOAuth2Token.
Is there anyway to wait() and get notified when startOAuth2Authentication returns after acquiring a token?
Auth.startOAuth2Authentication(this, getString(R.string.app_key));
//wait for response, retry, or time out and finish
String accessToken = Auth.getOAuth2Token();
prefs.edit().putString(ACCESS_TOKEN, accessToken).commit();
You shouldn't call startOAuth2Authentication twice, and you shouldn't call getOAuth2Token immediately after calling startOAuth2Authentication.
You should start the flow by calling startOAuth2Authentication as shown in the example here:
https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/UserActivity.java#L36
And then you should complete the flow by calling getOAuth2Token later in onResume as shown in the example here:
https://github.com/dropbox/dropbox-sdk-java/blob/master/examples/android/src/main/java/com/dropbox/core/examples/android/DropboxActivity.java#L22
Here is a simple example for implementing the Dropbox Android API:
https://www.sitepoint.com/adding-the-dropbox-api-to-an-android-app/
Now, to get to the point of your question, you will not be able to get a toke immediately after Auth.startOAuth2Authentication(this, getString(R.string.app_key)); is called. After you call this method, the Dropbox login activity is shown, and you can get the token only after the user logs in (which is in no way immediate, and you have no way of telling how long it will take).
After the user logs in successfully your activity will be resumed, and you can see in the example from the tutorial that the Activity's onResume method is overridden a check is performed in there.
I will copy below the LoginActivity from this tutorial. It should be easy enough to start from here:
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button SignInButton = (Button) findViewById(R.id.sign_in_button);
SignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Auth.startOAuth2Authentication(getApplicationContext(), getString(R.string.APP_KEY));
}
});
}
#Override
protected void onResume() {
super.onResume();
getAccessToken();
}
public void getAccessToken() {
String accessToken = Auth.getOAuth2Token(); //generate Access Token
if (accessToken != null) {
//Store accessToken in SharedPreferences
SharedPreferences prefs = getSharedPreferences("com.example.valdio.dropboxintegration", Context.MODE_PRIVATE);
prefs.edit().putString("access-token", accessToken).apply();
//Proceed to MainActivity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
}

Android Facebook login always ask for user after logout

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

Disable auto log in with Facebook loginbutton

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"));

How to LogOut from app with Facebook sdk 4 in android

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();
}

Android Facebook SDK: Check if the user is logged in or not

I'm have a feature on my Android app where the user authorizes the app and shares a link.
I also need to give an option for the user to logout of facebook and I need to conditionally disable this button if the user is not logged int (or not authorized the app).
I can't seem to find the API call on the Android SDK that would let me ask FB if the user is logged in or not.
What I have found is getAccessExpires():
Retrieve the current session's expiration time (in milliseconds since
Unix epoch), or 0 if the session doesn't expire or doesn't exist.
Will checking if the session equals 0 be the way to go? Or is there something I'm missing?
Facebook SDK 4.x versions have a different method now:
boolean loggedIn = AccessToken.getCurrentAccessToken() != null;
or
by using functions
boolean loggedIn;
//...
loggedIn = isFacebookLoggedIn();
//...
public boolean isFacebookLoggedIn(){
return AccessToken.getCurrentAccessToken() != null;
}
Check this link for better reference https://developers.facebook.com/docs/facebook-login/android
check this heading too "Access Tokens and Profiles" it says "You can see if a person is already logged in by checking AccessToken.getCurrentAccessToken() and Profile.getCurrentProfile()
I struggled to find a simple answer to this in the FB docs. Using the Facebook SDK version 3.0 I think there are two ways to check if a user is logged in.
1) Use Session.isOpened()
To use this method you need to retrieve the active session with getActiveSession() and then (here's the confusing part) decipher if the session is in a state where the user is logged in or not. I think the only thing that matters for a logged in user is if the session isOpened(). So if the session is not null and it is open then the user is logged in. In all other cases the user is logged out (keep in mind Session can have states other than opened and closed).
public boolean isLoggedIn() {
Session session = Session.getActiveSession();
return (session != null && session.isOpened());
}
There's another way to write this function, detailed in this answer, but I'm not sure which approach is more clear or "best practice".
2) Constantly monitor status changes with Session.StatusCallback and UiLifecycleHelper
If you follow this tutorial you'll setup the UiLifecycleHelper and register a Session.StatusCallback object with it upon instantiation. There's a callback method, call(), which you override in Session.StatusCallback which will supposedly be called anytime the user logs in/out. Within that method maybe you can keep track of whether the user is logged in or not. Maybe something like this:
private boolean isLoggedIn = false; // by default assume not logged in
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if (state.isOpened()) { //note: I think session.isOpened() is the same
isLoggedIn = true;
} else if (state.isClosed()) {
isLoggedIn = false;
}
}
};
public boolean isLoggedIn() {
return isLoggedIn;
}
I think method 1 is simpler and probably the better choice.
As a side note can anyone shed light on why the tutorial likes to call state.isOpened() instead of session.isOpened() since both seem to be interchangeable (session.isOpened() seems to just call through to the state version anyway).
Note to readers: This is now deprecated in the new FB 3.0 SDK.
facebook.isSessionValid() returns true if user is logged in, false if not.
Session.getActiveSession().isOpened()
returns true if user is logged in, false if not
Android Studio with :
compile 'com.facebook.android:facebook-android-sdk:4.0.1'
then check login like as:
private void facebookPost() {
//check login
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken == null) {
Log.d(TAG, ">>>" + "Signed Out");
} else {
Log.d(TAG, ">>>" + "Signed In");
}
}
#diljeet was right. https://stackoverflow.com/a/29375963/859330
In addition, use
return AccessToken.getAccessToken() != null && Profile.getCurrentProfile()!=null;
It always works this way.
For Facebook Android SDK 4.x you have to use the "AccessToken.getCurrentAccessToken()" as said by #Diljeet but his check didn't work for me, I finally checked it by doing:
Activity "onCreate":
facebookAccessToken = AccessToken.getCurrentAccessToken();
To check if the session is still active (I made it in the "onResume" method but do it where you need):
if(facebookAccessToken != null){
sessionExpired = facebookAccessToken.isExpired();
}else{
sessionExpired = true;
}
More info in https://developers.facebook.com/docs/facebook-login/android
This seems to be working quite well with the new sdk.
private boolean isFacebookLoggedIn(){
Session session = Session.getActiveSession();
if (session != null) {
//Session can be open, check for valid token
if (!session.isClosed()) {
if(!session.getAccessToken().equalsIgnoreCase("")){
return true;
}
}
}
return false;
}
I had the same issue. Here is my solution using SDK 4.0:
First of all, in your activity dealing with login check, be sure to call this primary:
FacebookSdk.sdkInitialize(this.getApplicationContext());
In your onCreate method put this :
updateWithToken(AccessToken.getCurrentAccessToken());
new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
updateWithToken(newAccessToken, handler);
}
};
Then add the method called:
private void updateWithToken(AccessToken currentAccessToken) {
if (currentAccessToken != null) {
fillUIWithFacebookInfos(handler);
} else {
login();
}
}
This way will handle the already logged in user and the newly logged in user.
I was using FB sdk for just for login..
Facebook developers reject my app, Because whenever user login, I send logout.. I dont matter user profile data... I just use FB for login.. FB tells if user login... dont send lgout...
I find Hacking way...
Now my app doesnot send logout whenever user login.... Whatever user login with,Google,Facebook,or normal.. When they click logout... In this three condition
I use
LoginManager.getInstance().logOut();
No matter which platform they use... There is no crash :)

Categories

Resources