I integrated Facebook login into my app, and It works fine. The issue is with the logout.
When I open the Facebook app on my device, I can perform a logout, so that the next time I open It, It will ask my If I want to login with my usual account, login with another account or even create a new account. Good, that is expected.
But this doesn't happen with my app. I mean, If the user opens my app, clicks in "logout" and the code below is ran
// Initialize Facebook SDK on the beginning.
FacebookSdk.sdkInitialize(this.getApplicationContext());
...
// Logout on user choice.
LoginManager.getInstance().logOut();
the next time he is back on the app and clicks to login he will be logged in directly with his account, he won't be asked with each account he wants to login.
I image that I need to clear all informations (tokens?) that are saved, which are being used into this directly login. Is this correct? If yes, how can I do it?
Thank you,
I am using this method. It's for SDK 4.6.0, but I guess it should be the same as 4.0. If not, just upgrade ;)
public void logoutFromFacebook(final LogoutFacebookListener listener) {
if (AccessToken.getCurrentAccessToken() == null) {
// already logged out
listener.onLoggedOutFromFacebook();
return;
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
listener.onLoggedOutFromFacebook();
}
}).executeAsync();
}
Listener:
public interface LogoutFromFacebookListener {
void onLoggedOutFromFacebook();
}
It seams like when you trying to login, facebook sdk uses your web browser (chrome, etc) in your case. And when you call LoginManager.getInstance().logOut(); you do logout just from facebook sdk, but you are still staying loggedin in your web browser. The Android and iOS SDKs don't currently support re-authentication. Hope they will be in future ;)
Related
I implemented Facebook login button as described in https://developers.facebook.com/docs/facebook-login/android developer guide with profile and email read permissions.
When i press login button, Facebook app opens up and then I can log in and can get user data from Facebook. After this point, Facebook button turns to Log out button automatically. And when it is pressed, it logs out. So far, it works well.
Once Facebook log out done in my app side, and want to re-login with Facebook button, Facebook fails with key hash error. If I go to account settings in Facebook app, and remove my app from list then re-login returns success.
I also tried the solution here Android Facebook app logout issue but it didn't work either.
To clear, I use this code (found shared pref name in AccessTokenCache class):
SharedPreferences fbSharedPreferences = this.getSharedPreferences("com.facebook.AccessTokenManager.SharedPreferences", 0);
if (fbSharedPreferences != null) {
fbSharedPreferences.edit().clear().commit();
}
I'm using Facebook SDK 4.5. I'm testing with a real Facebook account. My app keys and hashes are set in Facebook app settings.
P.S. Question title is influenced from Facebook Login-Logout Issue Invalid Key Hash Error, While Trying to Login Again (which does not have a solution).
I was having the same issue, you need to delete app from facebook app and then logout. Following function will do the trick.
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();
}
first, I'am sorry. i can't english well.
i have a problem in facebook sdk.
now i am developing login with facebook sdk.
and logout too.
but i can't find unlink api between my-app and facebook.
for example, some user using my app do not want to use my app more.
so he needs to ban me(or my app) in order to protect his data on facebook.
do you understand me? T.T please help me.
following flow is when the user unlinks the app himself directly.
but i want to do this in my app menu with login, logout, etc.
Menu Flow : (in facebook app settings) Apps -> Logged in with Facebook -> (choice a app) -> Remove App
FB.api("/me/permissions","DELETE",function(response){
console.log(response); //gives true on app delete success
});
You need a active access token of user to do this
Using Facebook sdk
new Request(
session,
"/me/permissions/{permission-to-revoke}",
null,
HttpMethod.DELETE,
new Request.Callback() {
public void onCompleted(Response response) {
/* handle the result */
}
}
).executeAsync();
Facebook has a very good documentation of integrating SDKs for Android, iOS & JavaScript etc. But still I have seen some confusions or misunderstandings regarding the exact ways to integrate Facebook SDK.
So I am writing all to the point steps to integrate Facebook SDK in Android Native apps and make use of Graph APIs etc.
In documentation, they have explained it in the way of documentation.
Here I am trying to explain the steps the way we need them while integrating in our app.
I will be giving answers to the most doubts we get, most occurring errors etc.
I hope it will help someone someday.
Facebook provides a wide range of options that can be done by integrating its SDK. But we need to follow some proper steps for the same.
Login
The very first thing we need to do is Login, before our app starts making use of Facebook SDK we need to do authentication. The user must login with his/her account before our app starts getting benefit from
This can be done in two ways,
a) Via Native Android App
If the user is having Facebook app installed in their phones then they will be asked to login via the account they have logged in with in their facebook app.
b) Via Web View
If user is not having facebook app, then facebook login page is opened in a web browser and user can login to their account.
So by any of these two options, once the user logs in then your app gets authenticated to use their account in your app.
How to do this
Once you include Facebook SDK & Library project in your own Android app then you can simply put their built in widget in any of Your xml file and you will see the Login button there. It's code is simple,
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp"
/>
Just include the above mentioned code in your XML file (where ever you want to show Facebook Login button.) It will automatically create the Login button like the following,
Confusions/Doubts/Questions we have in our minds up till this stage
Q. How can I create the button like this in my own app? From where am I going to get logo or what color does it have etc. etc.
Ans. We don't need to create it on our own, we just put that widget in our code and the button is created automatically.
Authorization
Okay, fine we have included the Facebook login button, now user can do login into our app, next what?
Next Facebook provides many kind of options we can do, like Share something on their profile, Post a status or custom story, get user's liked pages, access their messages, posts, feeds, friend list blah blah blah.
But it is not like that user logged in with their account and we can do anything we want in our app with their facebook account.
The next term which comes in to action is Permissions
To perform a specific task we need related permission, if the user will give you permission to do so with their Facebook account, only then our app will be able to do.
For example, to access user's likes we need user_likes permission, to post something on behalf of user on their profile we need publish_actions permission etc. Complete list of permissions can be found here
So after authentication, the next thing is authorization. What our app is authorized to do with user's account.
How to get permissions
As we have already created a Login button for facebook using their button widget, now we can provide the permissions as a list to that button, so it will let the user know about what permissions you want from them when they login with their account.
Clearing the doubt here
YES, the user will be told what permissions your app wants from them while doing login. Simply you can say, the user will be told what your app can do with their facebook account like accessing their friend list, post something on their profile, reading contacts etc. However the user may or may not read it, but the login button let them know about everything.
How to add permissions to Facebook login button
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status", "publish_actions"));
So you can see we are providing a list of permissions we want. However it is even possible to ask for more permissions later on, so it is more advisable to firstly ask for basic permissions and ask for permissions like publish_actions, when user would want it.
Session
Session is a very common term mostly in case of web applications. It serves the similar purpose here. Once the user logs in with their facebook account, a Session is created in your app with the facebook and it remains until the user logs out.
Q. How to show Facebook log out button?
Ans. You will be very happy to hear this, you don't need to do anything to show log out button, once the user logs in, the login button is automatically changed to logout button.
Benefit of Session
Session object has the authentication token that enables us to perform any action with Facebook SDK.
We can get the facebook session object at any time by calling the following method,
Session session = Session.getActiveSession();
UiLifecycleHelper class
Although we have done all the steps, but we need to maintain the session properly then we are going to need this class. We just need to put it in all our activity life cycle methods
so that the facebook session is maintained accordingly.
Define an instance variable in your activity,
private UiLifecycleHelper uiHelper;
Then add the following code,
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
Now the facebook session will be maintained automatically without your headache.
Calling the Graph API
I am going to give you a very simple and basic example here, suppose we want to get the list of the pages the user has liked, then we can do it with the following code,
Session session = Session.getActiveSession();
new Request(
session,
"/me/likes",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
//Do what you want to with the response
}
}
).executeAsync();
Q. How it is going to fetch data related to the current user? We have not mentioned any user id any where?
Ans. The answer to this question is that we are using me object here, which will automatically point to the current user who has logged in to using facebook account.
[ SOLVED MYSELF. SEE THE ANSWER FOR SOLUTION. ]
I used android facebook sdk 3.5 in my application for login. Now when user logout from facebook in my application, i simply follwing below codes to logout.
session=new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
Now, if user again try to login to facebook, I want to show login box as another user instead of doing login automatically from sessioncache.
[ remember that when your device has facebook application installed. Above problem only exist when device has facebook application else it is working fine. ]
I have googled this problem but not found the solution for SDK 3.5 . So how to force to show login box when user try to login again??
The only idea i got is we need to deauthorize our application on logout. So it will be asked to enter login again. Is this corret? if yes, then how can we deauthorize our app using sdk 3.5 ?
Finally i succeed in revoking authorization. here is the code.
Request deAuthorizeRequest=new Request(session, "/me/permissions", null, HttpMethod.DELETE, new Callback() {
#Override
public void onCompleted(Response response) {
((BaseFunctions) getActivity()).Log("unlink account : "+response.toString());
session.closeAndClearTokenInformation();
}
});
deAuthorizeRequest.executeAsync();
But it seems that this solved my problem partial. It is not showing login box dialog. Need to find solution for it. :)
Now i am working with android Facebook integration.But logout is not working on this.without logout from my browser in phone i can't logout from my application.why this happening?.How can we avoid this
There are two independent things going on here:
1) whether your user has authenticated your app (with permissions) to Facebook and
2) whether your user is logged in to Facebook.
Authentication is required the first time your user uses your app and lasts until the user explicitly de-authenticates (e.g. through the Facebook web Account Settings -> Apps -> App Settings).
Log in may be required each time your user starts your app. But if you use the default SDK authorize(), that tries to do a Single Sign On (SSO), where if the Facebook app is logged in, your app is automatically logged in and uses the existing access token.
If you are using SSO, when you do a logout, that has no effect, as a real logout would have to log out the Facebook app - which the user might not like!
You can get around this behavior by doing an authorize of the form
authorize(this, PERMISSIONS, FORCE_DIALOG_AUTH, new LoginDialogListener());
which avoids SSO and forces a dialog login. Of course, that then forces your user to login each time you start your app - unless you save the login details / access token under the
covers (which is what the SDK does - check the source).
EDITED:
m_facebook.authorize(FacebookActivity.this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
new LoginDialogListener());
class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle p_values)
{
saveCredentials(m_facebook);
if (m_messageToPost != null)
{
postToWall(m_messageToPost);
}
}
public void onFacebookError(FacebookError p_error)
{
finish();
}
public void onError(DialogError p_error)
{
finish();
}
public void onCancel()
{
finish();
}
}