如何使用 Facebook SDK 获取姓名和电子邮件

Posted

技术标签:

【中文标题】如何使用 Facebook SDK 获取姓名和电子邮件【英文标题】:How Do I Fetch Name and Email using Facebook SDK 【发布时间】:2015-05-19 05:38:17 【问题描述】:

我正在使用 TextView 显示登录 facebook 用户的姓名和电子邮件,但我真的不知道如何获取姓名和电子邮件?

private void onSessionStateChange(Session session, SessionState state,
                                  Exception exception) 
    if (session != currentSession) 
        return;
    

    if (state.isOpened()) 
        // Log in just happened.
        Toast.makeText(getApplicationContext(), "session opened",
                Toast.LENGTH_SHORT).show();
     else if (state.isClosed()) 
        // Log out just happened. Update the UI.
        Toast.makeText(getApplicationContext(), "session closed",
                Toast.LENGTH_SHORT).show();
    

【问题讨论】:

您还需要获得权限才能获取用户 Permissions.EMAIL 和 Permissions.BASIC_INFO 的基本信息以获取名字和电子邮件。 您使用的是哪个 Facebook SDK? @DarshanParikh 非常感谢您,将其发布为您的答案... 没关系。如果有帮助,您可以对此评论进行投票。 @DarshanParikh 兄弟,但我必须接受一个答案,我想接受我使用的答案,请发布我正在等待的答案.. 【参考方案1】:

您可以得到如下姓名和邮箱:

// use their Facebook info
    JSONObject json = Util.parseJson(facebook.request("me"));
    String facebookID = json.getString("id");
    String firstName = json.getString("first_name");
    String lastName = json.getString("last_name");
    Toast.makeText(uiActivity,"Thank you for Logging In, " 
                 + firstName + " " 
                 + lastName + "!"
                 , Toast.LENGTH_SHORT).show();

【讨论】:

【参考方案2】:

这是 facebook Sdk 4+ 的工作示例,您也可以关注此Link

这是你的 XML

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_
    android:layout_
    android:orientation="vertical">

 <com.facebook.login.widget.LoginButton
    android:id="@+id/connectWithFbButton"
    android:layout_
    android:layout_
    android:layout_centerInParent="true"
    android:layout_gravity="center_horizontal"
    android:text="  connect_with_facebook" />

      </LinearLayout>

把它放在 onCreate 中

      private LoginButton loginButton;
      CallbackManager callbackManager;

     loginButton = (LoginButton) findViewById(R.id.connectWithFbButton);

        loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday"));



        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() 
            @Override
            public void onSuccess(LoginResult loginResult) 
                // App code
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please Wait..");
                pDialog.setIndeterminate(false);
                pDialog.setCancelable(true);
                pDialog.show(); 

                 GraphRequest request = GraphRequest.newMeRequest(
                         loginResult.getAccessToken(),
                         new GraphRequest.GraphJSONObjectCallback() 
                             @Override
                             public void onCompleted(
                                     JSONObject object,
                                     GraphResponse response) 
                                 pDialog.dismiss();
                                 Log.d("Response",response.getJSONObject().toString());
                                 if (response.getError() != null) 
                                     // handle error
                                  else 
                                     String email = object.optString("email");
                                     String fname = object.optString("fname");
                                     String lname = object.optString("lname");
                                   Log.d("Email",email);
                                   Log.d("fname",fname);
                                   Log.d("lname",lname);
                              //     Log.d("Response", response.getInnerJsobject.toString());

                                 
                             
                         );
                 Bundle parameters = new Bundle();
                 parameters.putString("fields", "id,name,email,gender, birthday");
                 request.setParameters(parameters);
                 request.executeAsync();

            

            @Override
            public void onCancel() 
                // App code
                Log.d("LoginActivity", "cancel");
            

            @Override
            public void onError(FacebookException exception) 
                // App code
                 Log.d("LoginActivity", exception.getCause().toString());
            
        );

在你的 OnActivityResult 中写如下

@Override
  protected void onActivityResult(int requestCode, int responseCode, Intent intent) 
        callbackManager.onActivityResult(requestCode, responseCode, intent);
    

【讨论】:

【参考方案3】:

详情请参考:here

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());
                
            );
        
    

【讨论】:

以上是关于如何使用 Facebook SDK 获取姓名和电子邮件的主要内容,如果未能解决你的问题,请参考以下文章