如何使用Android Facebook sdk从Facebook获取好友列表?

时间:2015-11-11 17:15:31

标签: android facebook facebook-graph-api

我在Facebook上创建了一个应用程序,并实现了实施Facebook SDK的第一步。

这就是我要做的事情:从Facebook获取朋友列表,并能够从该列表中挑选一些朋友并将其导入我的应用程序。

我是怎么做到的?

1 个答案:

答案 0 :(得分:15)

您是否正在尝试将用户的Facebook好友列表登录到您的应用中?听起来你需要执行facebook图形请求来获取该列表,然后撤回你想要的朋友 https://developers.facebook.com/docs/graph-api/reference/user/friendlists/

如果你想在Android java中这样做,她就是一个例子:

    AccessToken token = AccessToken.getCurrentAccessToken();
        GraphRequest graphRequest = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
                try {
                    JSONArray jsonArrayFriends = jsonObject.getJSONObject("friendlist").getJSONArray("data");
                    JSONObject friendlistObject = jsonArrayFriends.getJSONObject(0);
                    String friendListID = friendlistObject.getString("id"); 
                    myNewGraphReq(friendListID);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    Bundle param = new Bundle();
    param.putString("fields", "friendlist", "members");
    graphRequest.setParameters(param);
    graphRequest.executeAsync();

由于“member”是“friendlist”中的边缘,您可以使用您的好友列表ID执行新请求以获取该特定好友列表的成员。 https://developers.facebook.com/docs/graph-api/reference/friend-list/members/

private void myNewGraphReq(String friendlistId) {
    final String graphPath = "/"+friendlistId+"/members/";
    AccessToken token = AccessToken.getCurrentAccessToken();
    GraphRequest request = new GraphRequest(token, graphPath, null, HttpMethod.GET, new GraphRequest.Callback() {
        @Override
        public void onCompleted(GraphResponse graphResponse) {
            JSONObject object = graphResponse.getJSONObject();
            try {
                JSONArray arrayOfUsersInFriendList= object.getJSONArray("data");  
                /* Do something with the user list */
                /* ex: get first user in list, "name" */
                JSONObject user = arrayOfUsersInFriendList.getJSONObject(0);
                String usersName = user.getString("name");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
     Bundle param = new Bundle();
    param.putString("fields", "name");
    request.setParameters(param);
    request.executeAsync();
}

在Facebook Graph请求的文档中,您可以看到可以使用User对象执行的操作。遗憾的是,我没有足够的代表来发布另一个链接。

请记住,用户必须已登录facebook以获取执行这些操作所需的访问令牌。

嗯,希望这是你想要的远程。

编辑:此方法不再有效,关于好友列表的第一个链接显示它自2018年4月4日起被弃用。