java Android Facebook SDK 4.X,如何获取电子邮件地址和 Facebook 访问令牌以将其传递给 Web 服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29517667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Facebook SDK 4.X , how to get Email address and Facebook Access Token to pass it to Web Service
提问by John
EDIT : My Question is how to get Email , UserId , Facebook Authentication with Facebook SDK 4.X , at this moment , with Ming Respond , i know how can i get Email , User Id , so my question is how to get Facebook Authentication since Session and GraphUser has just been replaced by LoginManager and AccessToken and there is no information about it?
编辑:我的问题是如何使用 Facebook SDK 4.X 获取电子邮件、用户 ID、Facebook 身份验证,此时,使用 Ming Respond,我知道如何获取电子邮件、用户 ID,所以我的问题是如何获取 Facebook 身份验证,因为Session 和 GraphUser 刚刚被 LoginManager 和 AccessToken 取代,没有相关信息?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import java.util.Arrays;
public class RegisterActivity extends Activity {
private String fbUserID;
private String fbProfileName;
private String fbAuthToken;
private LoginButton fbLoginBtn;
private static final String TAG = "FacebookLogin";
CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_activity);
fbLoginBtn = (LoginButton) findViewById(R.id.connect_with_facebook_button);
fbLoginBtn.setReadPermissions(Arrays.asList("email", "user_photos", "public_profile"));
fbLoginBtn.setBackgroundResource(R.drawable.connect_facebook_button);
accessTokenTracker = new AccessTokenTracker() {
@Override
protected void onCurrentAccessTokenChanged(
AccessToken oldAccessToken,
AccessToken currentAccessToken) {
fbAuthToken = currentAccessToken.getToken();
fbUserID = currentAccessToken.getUserId();
Log.d(TAG, "User id: " + fbUserID);
Log.d(TAG, "Access token is: " + fbAuthToken);
}
};
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(
Profile oldProfile,
Profile currentProfile) {
fbProfileName = currentProfile.getName();
Log.d(TAG, "User name: " + fbProfileName );
}
};
fbLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(
JSONObject user,
GraphResponse response) {
String id = user.optString("id");
String firstName = user.optString("first_name");
String lastName = user.optString("last_name");
String email = user.optString("email");
}
@Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
}
回答by Ming Li
fbLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String id = me.optString("id");
// send email and id to your web server
}
}
}).executeAsync();
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
回答by vishal dharankar
Easiest answer that i found after hours of searching is as follows,the highest voted answer didn't work for me and email was alway empty
经过数小时的搜索,我找到的最简单的答案如下,投票最高的答案对我不起作用,电子邮件总是空的
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object,GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if(json != null){
String text = json.getString("email");
Log.d("email",text);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
I believe setting parameters as required fields to the Graph Request is a crucial thing here. You can also use this code with LoginButton, works without issue.
我相信将参数设置为图形请求的必填字段在这里至关重要。您也可以将此代码与 LoginButton 一起使用,可以正常工作。
****** Update******** After using this code with many accounts found that if the email isn't verified it won't be returned, in such case following code helped along with abo
****** 更新******** 将此代码与许多帐户一起使用后发现,如果电子邮件未通过验证,则不会返回,在这种情况下,以下代码与 abo 一起帮助
facebookLoginButton.setReadPermissions("email");
Hope this helps further
希望这有助于进一步
回答by maros136
I must add extra field for user Email.
我必须为用户电子邮件添加额外的字段。
//register facebook login callback
LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>()
{
@Override
public void onSuccess (LoginResult loginResult)
{
Log.d(TAG, "FB: login success");
showLoading(true);
final String token = loginResult.getAccessToken().getToken();
//prepare fields with email
String[] requiredFields = new String[]{"email"};
Bundle parameters = new Bundle();
parameters.putString("fields", TextUtils.join(",", requiredFields));
GraphRequest requestEmail = new GraphRequest(loginResult.getAccessToken(), "me", parameters, null, new GraphRequest.Callback()
{
@Override
public void onCompleted (GraphResponse response)
{
if (response != null)
{
GraphRequest.GraphJSONObjectCallback callbackEmail = new GraphRequest.GraphJSONObjectCallback()
{
@Override
public void onCompleted (JSONObject me, GraphResponse response)
{
if (response.getError() != null)
{
Log.d(TAG, "FB: cannot parse email");
showDialog(getString(R.string.dialog_message_unknown_error));
showLoading(false);
}
else
{
String email = me.optString("email");
// send email and id to your web server
//...
}
}
};
callbackEmail.onCompleted(response.getJSONObject(), response);
}
}
});
requestEmail.executeAsync();
}
@Override
public void onCancel ()
{
Log.d(TAG, "FB: login cancel");
showDialog(getString(R.string.dialog_message_unknown_error));
}
@Override
public void onError (FacebookException e)
{
Log.d(TAG, "FB: login error " + e.getMessage());
showDialog(getString(R.string.dialog_message_unknown_error));
}
});