我試圖使用以下代碼通過我的應用獲取我的Facebook電子郵件地址,但返回值爲空。無法從Android的Facebook獲取電子郵件
public class MainActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private Button fb;
private LoginButton loginButton;
private AccessToken accessToken;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
fb = (Button) findViewById(R.id.fb);
loginButton = (LoginButton) findViewById(R.id.login_button);
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(
callbackManager,
new FacebookCallback <LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
accessToken= loginResult.getAccessToken();
GraphRequestAsyncTask request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject user, GraphResponse response) {
final Profile profile = Profile.getCurrentProfile();
if ((user != null) && (profile != null)) {
accessToken = AccessToken.getCurrentAccessToken();
if (accessToken.getDeclinedPermissions().isEmpty()) {
try {
String email = user.get("email").toString();
Log.e("facebook response email",email+"mm");
Log.e("facebook response",user.toString()+"mm");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}).executeAsync();
}
@Override
public void onCancel() {
}
@Override
public void onError(FacebookException exception) {
}
}
);
}
public void onClick(View v) {
if (v == fb) {
LoginManager.getInstance().logInWithReadPermissions(
this,
Arrays.asList("email","public_profile")
);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
Log.e("Token", "Token: " + accessToken.getToken());
Log.e("UserID", "UserID: " + accessToken.getUserId());
}
}
}
我寫了一些代碼,但結果是空? 我如何從Facebook SDK獲取電子郵件? 我不知道是什麼原因,但我可以使用Graph API Explorer獲取電子郵件地址。有沒有人知道這段代碼有什麼問題?
你需要指定你想要的字段 – WizKid
我想要來自Facebook的令牌和電子郵件。這都是@WizKid – BekaKK
我知道。當你向Facebook發出請求時,你必須指定你想要的字段。否則Facebook將不會將它們退還給您 – WizKid