How to integrate Facebook SDK into Native Android apps - android

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.

Related

Programmatically clear Facebook SDK 4.0 session on Android

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

Facebook Login with Read and Publish(Write) permissions

I am trying Facebook Login in Android with LoginManager class. I want read and write permissions during login only. The issue I am facing is , If I try with
LoginManager.getInstance().loginWithReadPermissions();
LoginManager.getInstance().loginWithPublishPermissions();
If Facebook App is not installed, Facebook WebView loads up, I enter credentials, I see two permissions screen (One for Read and One for write) and then again Login Screen.Which basically, creates bad user experience.
It happens because, both loginWithxxxPermissions() methods,starts a new login flow.But actually, It should not show Login Screen for already logged in user.
I am not able to find any method to pass the accessToken to let me the method know that, the new permission query is for already logged in user.
Anyone, Please help me out or suggest some other alternative, But the requirement is clear. I need Read/Write permissions without showing Login screen twice.

Destroy Facebook session completely in a custom Android Application using Facebook SDK 4.x.x

I am just new to Android Application and trying my hands on implementing Facebook login within my app. Successfully implementation of login but logout causes some trouble.
The first time I logged in it requested for my details and then signed in.
Next time I do the same it no more asks for my details, by default it logs me in with account.
What if I want to sign in with different user?
I have searched the net for solution and found out that -
- I cannot use Session as they were available only till Facebook SDK 3.X.X not for SDK 4.X.X
- I have tried calling LoginManager.getInstance().logOut();
(But I still have doubts where to use it.)
- I have also tried
new GraphRequest(AccessToken.getCurrentAccessToken(),"/me/permissions/", null, HttpMethod.DELETE,
new GraphRequest.Callback(){
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
}
}).executeAsync();
and I have also tried doing this :
` AccountManager am = AccountManager.get(context);
Account[] localAccounts = am.getAccounts();
for (int i=0; i<localAccounts.length; i++){
if (localAccounts[i].type.equals("com.facebook.auth.login")){
am.removeAccount(localAccounts[i], null, null);
}
}`
So it'll be really great if somebody could guide me properly on how to carry out a successful logout operation on Facebook, I'll be highly obliged.
Thanks in advance :)
The SDK will use either of two options to let the user log in to your app on Android:
using the native login dialog (which is powered by the Facebook app that is installed on the device)
using a webview-based dialog if the Facebook app is not installed on the device.
Both options depend on you being signed into Facebook in another app (your browser/your native Facebook app).
If you want to log into your app as a different user (there is really no need, because android system user profiles should be considered personal and individually owned), you need to go to the app you use for Facebook (native Facebook app/browser) and switch to a different profile there. After that you should be able to log into your app with that other profile.
Other than that, it is not your app's job to log people out of their Facebook.

Messing with Twitter login using both Fabric and Parse.com

I'm so confused. I started using parse.com, noted they had useful APIs for logging in with Twitter, and was doing:
Button login = (Button) findViewById(R.id.twitter_login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseTwitterUtils.logIn(this, ...)
}
});
So when clicking on login (a simple button of mine) I was being shown a floating dialog, and asked to give permissions to the app I registered on the Twitter Application Management.
Then I wanted to have the twitter-designed log-in button, of course, and so subscribed to io.fabric, installed Twitter APIs, and put a <com.twitter.sdk.android.core.identity.TwitterLoginButton/> element in my layout.
This button needs no click listener, because clicking on it brings up a new window where I am asked to give permissions to a fabric registered app which I wasn't even aware of, and that I can manage through the official Fabric website.
So
if I have a TwitterLoginButton and also set my parse.com click listener on it, I will be asked giving permission to two different apps (but these are the same app I'm working on!)
How to get elegantly out of this mess?
Is there something I can do to merge the two applications in these two different websites?
Should I stick to one approach or the other? I really need the user to sign on my parse.com database. But if only use ParseTwitterUtils, I won't have the login button (right?).
What is really happening when calling ParseTwitterUtils.logIn? Is it logging in the user into Twitter (and so I'll be able to use "share" functions and such), or just fetching user data into the parse.com database?
Wrote four questions, but what I'm really asking is what is the most used approach to this.

How to like facebook messages

In my application I have one expandable list view which displays Facebook messages.
When a user clicks the list view then a child view opens in that I have a button called Like. By clicking the Like button the original message should be liked in Facebook
One important thing is that it should not ask login details from the user. I searched a lot on the web but I find any good tutorial.
I don't have any basic idea of Facebook. Please provide me with some suggestions of how to do it.
Thanks
Well, if you want to like Facebook messages, you need to ask a permission for that with the Facebook SDK :
https://github.com/facebook/facebook-android-sdk
So Basically, you can do SSO with Facebook SDK, he will just ask for the permission needed if the user is already logged on his Facebook application.
Take a look at the sample on the Android SDK Facebook on the link above.
When you have the "like" permission (publish_stream), you can do it like that :
Request likeFacebook = new Request(Session.getActiveSession(), fBPostId + "/likes", null, HttpMethod.POST, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// analyse your response
}
});
Request.executeBatchAndWait(likeFacebook);

Categories

Resources