Android get Facebook friends who have app downloaded - android

I am using the Facebook Android SDK. Is there an easy way to get a user's friends who have downloaded the app? For example, the app Draw Something implements this. I can't seem to find any information on this subject
I would guess that if it was possible, some extra information would be needed in the httppost to access this information.

* Note: since 3.14 version, me/friends will only return friends that also use the app, so below implementation is deprecated. See the new "Invitable Friends" or "Taggable Friends" APIs for alternatives.
Using the new Facebook SDK for Android (3.0) is very easy to get your user's friend list.
Following is the code:
private void requestFacebookFriends(Session session) {
Request.executeMyFriendsRequestAsync(session,
new Request.GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users,
Response response) {
// TODO: your code for friends here!
}
});
}
Nevertheless, in order to get the user's friends who are using your Facebook app is a little bit complicated (due to Facebook API documentation). But yes, it is possible.
First of all, create your request:
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture",
"installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}
Note that you need to insert the field "installed" in your request. I'm requesting the user picture path with the same request. Check your possibilities here.
Next, you can use above code to create your request and then get your friends:
private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
List<GraphUser> friends = getResults(response);
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
Note that using this generic request, you don't receive a GraphUser list as response. You'll need following code to get the response as GraphUser list:
private List<GraphUser> getResults(Response response) {
GraphMultiResult multiResult = response
.getGraphObjectAs(GraphMultiResult.class);
GraphObjectList<GraphObject> data = multiResult.getData();
return data.castToListOf(GraphUser.class);
}
Now you can use your user's friend list, with the information if each of your friends use your Facebook app:
GraphUser user = friends.get(0);
boolean installed = false;
if(user.getProperty("installed") != null)
installed = (Boolean) user.getProperty("installed");

I implemented it in this way
Bundle params = new Bundle();
params.putString("fields", "name, picture, location, installed");
And during displaying of the items on the list,in the getView() method i did this
boolean b = jsonObject.getBoolean("installed");
if (b){
Log.d("VIVEK",jsonObject.getString("name"));
}

I hope this post helps you:
How can i get my friends using my facebook App with graph api asp.net
According to the Facebook SDK, the has_added_app field is deprecated and you should use the is_app_user

Related

i can't use oauth 2.0 to connect with my server using android

i'm new with android and i need to do a connection with server with oauth 2.0 i looked in internet and found just example how to dowit with google or github but my need is to connect with my own server i have the clientId clientSecret and the scope all i need is to get the token correctly
i hope my question is clear
thank you
this what i have donne
AccountManager am = AccountManager.get(Authentification.this);
Bundle options = new Bundle();
options.putSerializable("numero", numero);
am.getAuthToken(
null,
"whrite",
options,
this,
new OnTokenAcquired(),
null);
private class OnTokenAcquired implements AccountManagerCallback<Bundle> {
#Override
public void run(AccountManagerFuture<Bundle> result) {
// Get the result of the operation from the AccountManagerFuture.
try{
Bundle bundle = result.getResult();
// The token is a named value in the bundle. The name of the value
// is stored in the constant AccountManager.KEY_AUTHTOKEN.
String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
System.out.println("================>>>>"+token);
}catch(Exception e){
}
}
}
I would start with the AppAuth code sample. My blog post
has step by step instructions on how to run it.
Once it is working reconfigure it to point to your own Authorization Server.

Can you get a current users friendlist with facebook API? [duplicate]

I am trying to get my friend name and ids with Graph API v2.0, but data returns empty:
{
"data": [
]
}
When I was using v1.0, everything was OK with the following request:
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
But now I cannot get friends!
In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as 'by design'.
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
UPDATE: Facebook have published an FAQ on these changes here: https://developers.facebook.com/docs/apps/faq which explain all the options available to developers in order to invite friends etc.
Although Simon Cross's answer is accepted and correct, I thought I would beef it up a bit with an example (Android) of what needs to be done. I'll keep it as general as I can and focus on just the question. Personally I wound up storing things in a database so the loading was smooth, but that requires a CursorAdapter and ContentProvider which is a bit out of scope here.
I came here myself and then thought, now what?!
The Issue
Just like user3594351, I was noticing the friend data was blank. I found this out by using the FriendPickerFragment. What worked three months ago, no longer works. Even Facebook's examples broke. So my issue was 'How Do I create FriendPickerFragment by hand?
What Did Not Work
Option #1 from Simon Cross was not strong enough to invite friends to the app. Simon Cross also recommended the Requests Dialog, but that would only allow five requests at a time. The requests dialog also showed the same friends during any given Facebook logged in session. Not useful.
What Worked (Summary)
Option #2 with some hard work. You must make sure you fulfill Facebook's new rules: 1.) You're a game 2.) You have a Canvas app (Web Presence) 3.) Your app is registered with Facebook. It is all done on the Facebook developer website under Settings.
To emulate the friend picker by hand inside my app I did the following:
Create a tab activity that shows two fragments. Each fragment shows a list. One fragment for available friend (/me/friends) and another for invitable friends (/me/invitable_friends). Use the same fragment code to render both tabs.
Create an AsyncTask that will get the friend data from Facebook. Once that data is loaded, toss it to the adapter which will render the values to the screen.
Details
The AsynchTask
private class DownloadFacebookFriendsTask extends AsyncTask<FacebookFriend.Type, Boolean, Boolean> {
private final String TAG = DownloadFacebookFriendsTask.class.getSimpleName();
GraphObject graphObject;
ArrayList<FacebookFriend> myList = new ArrayList<FacebookFriend>();
#Override
protected Boolean doInBackground(FacebookFriend.Type... pickType) {
//
// Determine Type
//
String facebookRequest;
if (pickType[0] == FacebookFriend.Type.AVAILABLE) {
facebookRequest = "/me/friends";
} else {
facebookRequest = "/me/invitable_friends";
}
//
// Launch Facebook request and WAIT.
//
new Request(
Session.getActiveSession(),
facebookRequest,
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if (error != null && response != null) {
Log.e(TAG, error.toString());
} else {
graphObject = response.getGraphObject();
}
}
}
).executeAndWait();
//
// Process Facebook response
//
//
if (graphObject == null) {
return false;
}
int numberOfRecords = 0;
JSONArray dataArray = (JSONArray) graphObject.getProperty("data");
if (dataArray.length() > 0) {
// Ensure the user has at least one friend ...
for (int i = 0; i < dataArray.length(); i++) {
JSONObject jsonObject = dataArray.optJSONObject(i);
FacebookFriend facebookFriend = new FacebookFriend(jsonObject, pickType[0]);
if (facebookFriend.isValid()) {
numberOfRecords++;
myList.add(facebookFriend);
}
}
}
// Make sure there are records to process
if (numberOfRecords > 0){
return true;
} else {
return false;
}
}
#Override
protected void onProgressUpdate(Boolean... booleans) {
// No need to update this, wait until the whole thread finishes.
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
/*
User the array "myList" to create the adapter which will control showing items in the list.
*/
} else {
Log.i(TAG, "Facebook Thread unable to Get/Parse friend data. Type = " + pickType);
}
}
}
The FacebookFriend class I created
public class FacebookFriend {
String facebookId;
String name;
String pictureUrl;
boolean invitable;
boolean available;
boolean isValid;
public enum Type {AVAILABLE, INVITABLE};
public FacebookFriend(JSONObject jsonObject, Type type) {
//
//Parse the Facebook Data from the JSON object.
//
try {
if (type == Type.INVITABLE) {
//parse /me/invitable_friend
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
// Handle the picture data.
JSONObject pictureJsonObject = jsonObject.getJSONObject("picture").getJSONObject("data");
boolean isSilhouette = pictureJsonObject.getBoolean("is_silhouette");
if (!isSilhouette) {
this.pictureUrl = pictureJsonObject.getString("url");
} else {
this.pictureUrl = "";
}
this.invitable = true;
} else {
// Parse /me/friends
this.facebookId = jsonObject.getString("id");
this.name = jsonObject.getString("name");
this.available = true;
this.pictureUrl = "";
}
isValid = true;
} catch (JSONException e) {
Log.w("#", "Warnings - unable to process Facebook JSON: " + e.getLocalizedMessage());
}
}
}
Facebook has revised their policies now. You can’t get the whole friendlist anyway if your app does not have a Canvas implementation and if your app is not a game. Of course there’s also taggable_friends, but that one is for tagging only.
You will be able to pull the list of friends who have authorised the app only.
The apps that are using Graph API 1.0 will be working till April 30th, 2015 and after that it will be deprecated.
See the following to get more details on this:
User Friends
Facebook Application Development FAQ
In Swift 4.2 and Xcode 10.1:
If you want to get the friends list from Facebook, you need to submit your app for review in Facebook. See some of the Login Permissions:
Login Permissions
Here are the two steps:
1) First your app status is must be in Live
2) Get required permissions form Facebook.
1) Enable our app status live:
Go to the apps page and select your app
https://developers.facebook.com/apps/
Select status in the top right in Dashboard.
Submit privacy policy URL
Select category
Now our app is in Live status.
One step is completed.
2) Submit our app for review:
First send required requests.
Example: user_friends, user_videos, user_posts, etc.
Second, go to the Current Request page
Example: user_events
Submit all details
Like this submit for all requests (user_friends , user_events, user_videos, user_posts, etc.).
Finally submit your app for review.
If your review is accepted from Facebook's side, you are now eligible to read contacts, etc.
As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.
this is against Facebook policy, so depending on the country where you live, this may not be legal
you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
this is bypassing the OAuth concept
on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API
Sample implementation using WatiN:
class FacebookUser
{
public string Name { get; set; }
public long Id { get; set; }
}
public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
var users = new List<FacebookUser>();
Settings.Instance.MakeNewIeInstanceVisible = false;
using (var browser = new IE("https://www.facebook.com"))
{
try
{
browser.TextField(Find.ByName("email")).Value = email;
browser.TextField(Find.ByName("pass")).Value = password;
browser.Form(Find.ById("login_form")).Submit();
browser.WaitForComplete();
}
catch (ElementNotFoundException)
{
// We're already logged in
}
browser.GoTo("https://www.facebook.com/friends");
var watch = new Stopwatch();
watch.Start();
Link previousLastLink = null;
while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
{
var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).LastOrDefault();
if (lastLink == null || previousLastLink == lastLink)
{
break;
}
var ieElement = lastLink.NativeElement as IEElement;
if (ieElement != null)
{
var htmlElement = ieElement.AsHtmlElement;
htmlElement.scrollIntoView();
browser.WaitForComplete();
}
previousLastLink = lastLink;
}
var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
&& l.GetAttributeValue("data-hovercard").Contains("user.php")
&& l.Text != null
).ToList();
var idRegex = new Regex("id=(?<id>([0-9]+))");
foreach (var link in links)
{
string hovercard = link.GetAttributeValue("data-hovercard");
var match = idRegex.Match(hovercard);
long id = 0;
if (match.Success)
{
id = long.Parse(match.Groups["id"].Value);
}
users.Add(new FacebookUser
{
Name = link.Text,
Id = id
});
}
}
return users;
}
Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.
Try /me/taggable_friends?limit=5000 using your JavaScript code
Or
try the Graph API:
https://graph.facebook.com/v2.3/user_id_here/taggable_friends?access_token=
If you are still struggling with this issue on a development mode.
Follow the same process as mentioned below:
create a test app of your main app,
create test users, automatically install app for test users and assign them 'user_friend' permission.
Add your test users as a friend with each other.
I followed the same process after going through alot of research and finally it worked.
In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.
Each user must grant the user_friends permission in order to appear in the response to /me/friends.
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if (fbloginresult.grantedPermissions.contains("email")) {
// Do the stuff
}
else {
}
}
else {
}
}
}
So at the time of Facebook login, it prompts with a screen which contain all the permissions:
If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed
if ((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print(result!)
}
})
}
The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.
{
data = (
{
id = xxxxxxxxxx;
name = "xxxxxxxx";
}
);
paging = {
cursors = {
after = xxxxxx;
before = xxxxxxx;
};
};
summary = {
"total_count" = 8;
};
}

Get My Friend list form Facebook?

I am creating an application. I want to access the friends list form Facebook in my app, but i am unable to access the Facebook friends list in my app. All others thinks are accessible, only friend list is not accessible. I have an old app id in which i access all the friends but in my new app id i am unable to access the friend list. In my app, I mention the following permissions:
1. Public_Profiles
2. basic_info
3. user_photos
4. user friends
5. read_friendslist
if any others permissions are needed then please let me know.
You new app is using API v2.0 and in API v2.0 you can not get all friends. /me/friends will only return friends that are also using the app.
There are some new APIs added in v2.0 that you may be able to use: taggable_friends, invitable_friends and social context.
I am getting friends list in two ways:
`Session activeSession = Session.getActiveSession();
if (activeSession.getState().isOpened()) {
Request friendRequest = Request.newMyFriendsRequest(activeSession,
new GraphUserListCallback() {
#Override
public void onCompleted(List<GraphUser> users,
Response response) {
UsefullData.Log("Response : " + response.toString());
UsefullData.Log("Friends list" + users);
//setUserFriendsList(users);
}
});
Bundle params = new Bundle();
params.putString("fields", "id, name, picture");
friendRequest.setParameters(params);
friendRequest.executeAsync();
}`
Request friendRequest = new Request(
activeSession,
"/me/friends",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
UsefullData.Log("Friends Response : " + response.toString());
//setUserFriendsList(response);
}
}
);friendRequest.executeAsync();
Note: set custome permission "user_friends" in your session.
both codes are working at my end. I hope it will help for you.

Facebook permissions - requesting additional permissions

I want to get a list of a users albums names and ids. You need to add the permission users_photos for this.
I created a method called fetchAlbums, and in it I am requesting additional permissions. But by the time the permissions dialog pops up, the rest of the method has already executed (without the needed permissions!).
Whats the best way to do this, add the permissions in the onCreate of the Activity?
private void fetchAlbumsFromFB() {
Session session = Session.getActiveSession();
// make a new async request
Bundle params = new Bundle();
params.putString("fields", "id, name");
new Request(
session,
"/me/albums",
params,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
// use response id to upload photo to that album
//errText.setText("New Album created response: " + response.toString());
//need to get the newly created album ID.
try{
JSONObject graphResponse =response.getGraphObject().getInnerJSONObject();
Toast.makeText(getApplicationContext(), "Albums " + graphResponse.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
albID = null;
}
}
}
).executeAsync();
}
It's better to ask for user_photos permission at the starting point, when the user is authenticating the app the first time.
Since it's not an extended/publish permission, it will be asked along with the basic permissions and user wont bother too; else user will see the permission dialogs again and again that could frustrate him.
I guess, in that case this problem will be solved too.

How to track Facebook appRequest that send from Unity app?

I want to track invites that send from "player_1" to other players to count them and as result give "player_1" some reward. Like in PVZ2.
Ok, Facebook have SDK for Unity3d. Here is API to call App request dialog that allow to invite player:
public static void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
Facebook doc says something about redirect_url that could be used to track user's that accept indentations:
https://developers.facebook.com/docs/reference/dialogs/requests/
But Unity plugin doesn't have this param.
Also doc says that follow:
Requests are only available for games on Facebook.com or iOS and
Android apps. Accepting a request from a game will direct the person
to the Canvas Page URL of the app that sent the Request. For native
mobile apps, accepting the request will direct the person to the app
on their device if installed or to the appropriate location (Apple App
Store or Google Play) to download the app otherwise.
Game is going to work on mobile devices only. Therefore we don't need to make Facebook Canvas application. Should I implement this Canvas URL script on our website anyway?
Where is the correct place to inject code (server side script) to track Facebook app requests?
UPDATE:
Thanks to Bhavesh Vadalia for answer: https://stackoverflow.com/a/21597185/425707
I've decided to not handle friends requests in Canvas App.
Here is solution for Facebook SDK 5.0.3:
// Quesry string: "/fql?q=SELECT uid, name, is_app_user, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND is_app_user = 1";
string q = "/fql?q=SELECT+uid,+name,+is_app_user,+pic_square+FROM+user+WHERE+uid+IN+(SELECT+uid2+FROM+friend+WHERE+uid1+=+me())+AND+is_app_user+=+1";
FB.API(q, Facebook.HttpMethod.GET, friendsResult =>
{
if (friendsResult.Error != null)
{
FbDebug.Error(friendsResult.Error);
}
else
{
FbDebug.Log(friendsResult.Text);
}
});
Here is implement for track code using facebook graph api implement in for my application. hope it also help to you.
I am using facebook 3.6 sdk
private void requestMyAppFacebookFriends(Session session) {
Request friendsRequest = createRequest(session);
friendsRequest.setCallback(new Request.Callback() {
#Override
public void onCompleted(Response response) {
List<GraphUser> friends = getResults(response);
Log.e("RESULT : ", "#"+friends.size());
for(int i =0;i<friends.size(); i++){
GraphUser user = friends.get(i);
boolean installed = false;
if(user.getProperty("installed") != null){
installed = (Boolean) user.getProperty("installed");
}
if(installed){
Log.e("USER NAME", "#"+friends.get(i).getId());
}
}
// TODO: your code here
}
});
friendsRequest.executeAsync();
}
private Request createRequest(Session session) {
Request request = Request.newGraphPathRequest(session, "me/friends", null);
Set<String> fields = new HashSet<String>();
String[] requiredFields = new String[] { "id", "name", "picture","installed" };
fields.addAll(Arrays.asList(requiredFields));
Bundle parameters = request.getParameters();
parameters.putString("fields", TextUtils.join(",", fields));
request.setParameters(parameters);
return request;
}

Categories

Resources