如何通过android中的访问令牌获取Facebook用户的性别

时间:2018-05-31 03:24:15

标签: android firebase facebook-login facebook-android-sdk facebook-sdk-4.0

在Android Studio中,使用facebook SDK GraphRequest和令牌,我可以获取帐户信息,但性别除外。

这是我尝试的脚本:

GraphRequest request = GraphRequest.newMeRequest(token, (object, response) -> {
    Log.e("fbLoginActivity", object.toString());

    String fbId;
    String fbEmail;
    String fbFirst_name;
    String fbLast_name;
    String fbBirthday;
    String fbGender;
    String fbPhoto;

    try {
        String fbId = object.getString("id");
        String fbEmail = object.getString("email");
        String fbFirst_name = object.getString("first_name");
        String fbLast_name = object.getString("last_name");
        String fbBirthday = object.getString("birthday");
        String fbGender = object.getString("gender"); // <-- ERROR, but when I comment this line, it works (without gender data)
        String fbPhoto = "http://graph.facebook.com/" + fbId + "/picture?type=large";
    } catch (JSONException e) {
        Toast.makeText(mContext, "fb graph JSONException error", Toast.LENGTH_SHORT).show();
    }
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,first_name,last_name,email,gender,birthday,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();

这是我使用faceook登录时的读取权限:

fbLoginManager.logInWithReadPermissions(
    LoginActivity.this,
    Arrays.asList("email", "public_profile", "user_birthday", "user_photos")
);

问题出在这一行:

String fbGender = object.getString("gender");

所以我查看了object.toString(),实际上API中没有输出性别属性:

Log.e("fbLoginActivity", object.toString());

您知道获取Facebook用户性别的任何工作方式吗?

2 个答案:

答案 0 :(得分:1)

这里似乎没有有用的答案。我自己解决了这件好事!

问题在于我的读取权限,我只需在"user_gender"电话上添加fbLoginManager.logInWithReadPermissions()即可。以前,我虽然性别信息包含在"public_profile"中,但没有。

我的完整阅读权限代码:

fbLoginManager.logInWithReadPermissions(
        LoginActivity.this,
        Arrays.asList("email", "public_profile", "user_birthday", "user_gender", "user_link", "user_photos")
);

现在我的对象有性别属性,object.toString()结果:

{
    "id": // ...
    "first_name":"Taufik",
    "last_name":"Nur Rahmanda",
    "email":"topexgames@yahoo.com",
    "gender":"male", // <-- YEAH!
    "birthday":"07/26/1993",
    // ... etc
}

文件:

https://developers.facebook.com/docs/facebook-login/permissions/v3.0#permissions

答案 1 :(得分:0)

Facebook不支持使用Graph API获取性别和真实的Facebook用户ID。

你需要找到其他方法来获得性别,可能你需要一个图书馆来根据名字或其他东西找到性别。

您可以查看此答案here.

相关问题