如何使用Facebook的SDK的Android得到Facebook的照片,姓名,性别(How to

2019-07-18 18:56发布

我工作的一个Android应用程序中,任谁正在使用我们的应用登录Facebook的Android版用户,我需要提取他的照片,他的性别,他从Facebook的全名。 我使用Facebook的SDK这一点。

与Facebook SDK的帮助下,我能够登录到Facebook上,但我不知道如何从Facebook的提取他的照片,性别和姓名?

下面是我使用的登录到Facebook的代码。 我跟着这个教程

public class SessionLoginFragment extends Fragment {

    private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";

    private TextView textInstructionsOrLink;
    private Button buttonLoginLogout;
    private Session.StatusCallback statusCallback = new SessionStatusCallback();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment, container, false);

    buttonLoginLogout = (Button) view.findViewById(R.id.buttonLoginLogout);
    textInstructionsOrLink = (TextView) view.findViewById(R.id.instructionsOrLink);

    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
        session = Session.restoreSession(getActivity(), null, statusCallback,
            savedInstanceState);
        }
        if (session == null) {
        session = new Session(getActivity());
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
        }
    }

    updateView();

    return view;
    }

    @Override
    public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
    }

    private void updateView() {
    Session session = Session.getActiveSession();
    if (session.isOpened()) {
        Log.d("Hello", URL_PREFIX_FRIENDS + session.getAccessToken());
        Intent i = new Intent(getActivity(), ThesisProjectAndroid.class);
        startActivity(i);

    } else {
        Log.d("Hello", "Login Failed");
        textInstructionsOrLink.setText(R.string.instructions);
        buttonLoginLogout.setText(R.string.login);
        buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            onClickLogin();
        }
        });
    }
    }

    private void onClickLogin() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
    } else {
        Session.openActiveSession(getActivity(), this, true, statusCallback);
    }
    }

    private void onClickLogout() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
    }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        updateView();
    }
    }
}

谁能告诉我在哪里,我需要在上述类的变化得到我所需要的所有三个信息。 据我知道,如果我能得到Facebook的唯一ID的那个人,我可以得到所有我猜的信息。 有什么想法吗?

Answer 1:

在你StatusCallback功能,你可以从细节GraphUser对象

private class SessionStatusCallback implements Session.StatusCallback {
    private String fbAccessToken;

    @Override
    public void call(Session session, SessionState state, Exception exception) {
        updateView();
        if (session.isOpened()) {
            fbAccessToken = session.getAccessToken();
            // make request to get facebook user info
            Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
                @Override
                public void onCompleted(GraphUser user, Response response) {
                    Log.i("fb", "fb user: "+ user.toString());

                    String fbId = user.getId();
                    String fbAccessToken = fbAccessToken;
                    String fbName = user.getName();
                    String gender = user.asMap().get("gender").toString();
                    String email = user.asMap().get("email").toString();

                    Log.i("fb", userProfile.getEmail());
                }
            });
        }
    }
}


Answer 2:

随着新的API和Facebook上的自定义按钮,你可以使用下面的代码:

下面放的gradle在gradle这个文件:

 compile 'com.facebook.android:facebook-android-sdk:4.20.0'

  Newer sdk does not need initializaion .

    private CallbackManager callbackManager;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(LoginActivity.this);//Is now depricated
    setContentView(R.layout.activity_login);
    callbackManager = CallbackManager.Factory.create();
    }

onActivityResult:

        @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
         }

按钮点击:

   @Override
    public void onClick(View v) {
    switch (v.getId())
    {
        case R.id.btn_f_sign_in_login:
            LoginManager.getInstance().logInWithReadPermissions(
                    this,
                    Arrays.asList("user_friends", "email", "public_profile"));

            LoginManager.getInstance().registerCallback(callbackManager,
                    new FacebookCallback<LoginResult>() {
                        @Override
                        public void onSuccess(LoginResult loginResult) {
                            setFacebookData(loginResult);
                        }

                        @Override
                        public void onCancel() {
                        }

                        @Override
                        public void onError(FacebookException exception) {
                        }
                    });
            break;
    }
}

setFacebookData:

     private void setFacebookData(final LoginResult loginResult)
       {
    GraphRequest request = GraphRequest.newMeRequest(
            loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    // Application code
                    try {
                        Log.i("Response",response.toString());

                        String email = response.getJSONObject().getString("email");
                        String firstName = response.getJSONObject().getString("first_name");
                        String lastName = response.getJSONObject().getString("last_name");
                        String gender = response.getJSONObject().getString("gender");



                        Profile profile = Profile.getCurrentProfile();
                        String id = profile.getId();
                        String link = profile.getLinkUri().toString();
                        Log.i("Link",link);
                        if (Profile.getCurrentProfile()!=null)
                        {
                            Log.i("Login", "ProfilePic" + Profile.getCurrentProfile().getProfilePictureUri(200, 200));
                        }

                       Log.i("Login" + "Email", email);
                        Log.i("Login"+ "FirstName", firstName);
                        Log.i("Login" + "LastName", lastName);
                        Log.i("Login" + "Gender", gender);


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,email,first_name,last_name,gender");
    request.setParameters(parameters);
    request.executeAsync();
}

得到Facebook好友谁downoaded您的应用程序:

更换parameters.putString( “田”, “ID,电子邮件,名字,姓氏”);

parameters.putString( “田”, “ID,电子邮件,名字,姓氏,朋友”);

下面添加逻辑得到朋友的数据

                if (object.has("friends")) {
                  JSONObject friend = object.getJSONObject("friends");
                  JSONArray data = friend.getJSONArray("data");
                  for (int i=0;i<data.length();i++){
                 Log.i("idddd",data.getJSONObject(i).getString("id"));
                  }
             }


Answer 3:

新的API

private void importFbProfilePhoto() {

    if (AccessToken.getCurrentAccessToken() != null) {

        GraphRequest request = GraphRequest.newMeRequest(
                AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject me, GraphResponse response) {

                        if (AccessToken.getCurrentAccessToken() != null) {

                            if (me != null) {

                                String profileImageUrl = ImageRequest.getProfilePictureUri(me.optString("id"), 500, 500).toString();
                                Log.i(LOG_TAG, profileImageUrl);

                            }
                        }
                    }
                });
        GraphRequest.executeBatchAsync(request);
    }
}


Answer 4:

请参见以下教程

你必须要在获得GraphUser-对象的请求。 有了这个对象,你可以得到你想要的信息:GraphUser user.getName();user.getId(); 等等



Answer 5:

如果你会得到空的个人资料,然后使用档案跟踪如果(Profile.getCurrentProfile()== NULL){

            mProfileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
                    // profile2 is the new profile
                    Log.d("facebook - profile", profile2.getFirstName());
                    profile_firstname=profile2.getFirstName();
                    profile_lastname=profile2.getLastName();
                   // Toast.makeText(LoginActivity.this, "User ID : "+ profile2.getFirstName(), Toast.LENGTH_LONG).show();
                    mProfileTracker.stopTracking();
                }
            };

        }


Answer 6:

随着SDK v4.28和登录的用户上的问题,很容易与调用Profile.getCurrentProfile()内(或之后)的成功回调LoginManager

facebookCallbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(facebookCallbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult{ 
                    //Profile.getCurrentProfile()
                }
                @Override
                public void onCancel() {
                }
                @Override
                public void onError(FacebookException exception) {
                }
            });

你可以使用图形API ,但文件直接说使用上面的登录用户。



文章来源: How to get Facebook photo, full name, gender using Facebook SDK android