如何在Graph 3.0 API Android中获取Facebook帐户的性别和年龄范围

时间:2018-07-15 16:00:13

标签: android facebook-graph-api

自从Facebook在提供用户数据方面变得更加安全以来,事情已经发生了巨大变化。使用Bundles和Graph Request之前,我可以使用Graph 2.12在管理员帐户中获取性别和年龄范围。

  //Log in Facebook
private void signInFacebook() {

    //Request a read permission of user's info from Facebook
    //Data provided by Facebook will be used for Firebase FireStore
    LoginManager.getInstance().logInWithReadPermissions(LogIn.this, Arrays.asList("email", "public_profile"));

    LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(final LoginResult loginResult) {

            mStateOfSuccess = false;
            //Dismiss any snackbar first before showing a new one
            mSnackBar.dismiss();
            mSnackBar.show();

            Log.d(TAG, "facebook:onSuccess:" + loginResult);

            //Bundle is use for passing data as K/V pair like a Map
            Bundle bundle=new Bundle();
            //Fields is the key of bundle with values that matched the proper Permissions Reference provided by Facebook
            bundle.putString("fields","id, email, first_name, last_name, gender, age_range");

            //Graph API to access the data of user's facebook account
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("Login Success", response.toString());

                            //For safety measure enclose the request with try and catch
                            try {

                                //The get() or getString() key should be included in Bundle otherwise it won't work properly
                                //If not then error dialog will be called

                                //First re-initialize jSON object to a new Contructor with parameter that is equal to a jSON format age range
                                JSONObject ageRange  = new JSONObject(object.getString("age_range"));

                                        //Log in using Facebook with Firebase
                                        loginToFirebaseUsingFacebook(loginResult.getAccessToken()
                                                ,object.getString("first_name")
                                                ,object.getString("last_name")
                                                //Then get again get a string from object itself for the minimum age range
                                                //The idea is that we need to get minimum age only written im string format
                                                //not the whole age range data that is written in jSOM format
                                                ,ageRange.getString("min")
                                                ,object.getString("gender")
                                                ,object.getString("email")
                                        );

                            }
                            //If no data has been retrieve throw some error
                            catch (JSONException e) {
                               ErrorDialog(e.getMessage(),"facebookAuth");
                            }

                        }
                    });


            //Set the bundle's data as Graph's object data
            request.setParameters(bundle);

            //Execute this Graph request asynchronously
            request.executeAsync();

        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            ErrorDialog("Request has canceled.","facebookAuth");
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            ErrorDialog(String.valueOf(error),"facebookAuth");
        }
    });


}

但是现在一切都变了,即使访问我自己的帐户(admin)也无法提供我所需的数据。根据他们的文档enter image description here

1 个答案:

答案 0 :(得分:1)

我弄清楚了如何在Graph 3.0中做到这一点,您需要做的就是将此user_age_rangeuser_gender包括到权限中,并且现在可以按预期使用使用管理员帐户运行登录(如果应用尚未通过Facebook验证)。

  //Log in Facebook
private void signInFacebook() {

    //Request a read permission of user's info from Facebook
    //Data provided by Facebook will be used for Firebase FireStore
    //For more updates about Read Permissions - User Attributes: ''https://developers.facebook.com/docs/facebook-login/permissions/''
    LoginManager.getInstance().logInWithReadPermissions(LogIn.this, Arrays.asList("email","public_profile","user_gender","user_age_range"));

    LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(final LoginResult loginResult) {

            mStateOfSuccess = false;
            //Dismiss any snackbar first before showing a new one
            mSnackBar.dismiss();
            mSnackBar.show();

            Log.d(TAG, "facebook:onSuccess:" + loginResult);

            //Bundle is use for passing data as K/V pair like a Map
            Bundle bundle=new Bundle();
            //Fields is the key of bundle with values that matched the proper Permissions Reference provided by Facebook
            bundle.putString("fields","id,email,first_name,last_name,gender,age_range");

            //Graph API to access the data of user's facebook account
            GraphRequest request = GraphRequest.newMeRequest(
                    loginResult.getAccessToken(),
                    new GraphRequest.GraphJSONObjectCallback() {
                        @Override
                        public void onCompleted(JSONObject object, GraphResponse response) {
                            Log.v("Login Success", response.toString());

                            //For safety measure enclose the request with a try and catch
                            try {

                                //The get() or getString() key should be included in Bundle otherwise it won't work properly
                                //If not then error dialog will be called

                                //First re-initialize jSON object to a new Contructor with parameter that is equal to a jSON format age range
                                JSONObject ageRange  = new JSONObject(object.getString(getResources().getString(R.string.age_range)));

                                        //Log in using Facebook with Firebase
                                        loginToFirebaseUsingFacebook(loginResult.getAccessToken()
                                                ,object.getString(getResources().getString(R.string.fname))
                                                ,object.getString(getResources().getString(R.string.lname))
                                                //Then get again get a string from object itself for the minimum age range
                                                //The idea is that we need to get minimum age only written im string format
                                                //not the whole age range data that is written in jSON format
                                                ,ageRange.getString(getResources().getString(R.string.minimum))
                                                ,object.getString(getResources().getString(R.string.gender).toLowerCase())
                                                ,object.getString(getResources().getString(R.string.mail))
                                        );

                            }
                            //If no data has been retrieve throw some error
                            catch (JSONException e) {

                                //Log in using Facebook with Firebase
                                try {
                                    loginToFirebaseUsingFacebook(loginResult.getAccessToken()
                                            ,object.getString(getResources().getString(R.string.fname))
                                            ,object.getString(getResources().getString(R.string.lname))
                                            //Exception occurs if age and gender has no value
                                            ,null
                                            ,null
                                            ,object.getString(getResources().getString(R.string.mail))
                                    );
                                } catch (JSONException e1) {
                                    ErrorDialog(e.getMessage(),"facebookAuth");
                                }

                            }

                        }
                    });


            //Set the bundle's data as Graph's object data
            request.setParameters(bundle);

            //Execute this Graph request asynchronously
            request.executeAsync();

        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            ErrorDialog("Request has canceled.","facebookAuth");
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            ErrorDialog(String.valueOf(error),"facebookAuth");
        }
    });


}