android - Profile.getCurrentProfile() 登录后返回 null (FB API v4.0)

标签 android facebook

出于某种原因,Profile.getCurrentProfile() 有时会在使用 FB API v4.0 登录 FaceBook 后立即显示为 null。

这给我的应用程序带来了问题,因为我无法显示我的下一个 Activity,而 Profile 为空。

有时我说它为 null 的原因是,如果我关闭我的应用并重新打开它,我可以进入我的下一个 Activity,但如果我还没有登录,然后登录,Profile 为空。好像是很短的时间。

有解决办法或解决办法吗?

最佳答案

喜欢 Hardy said ,您必须创建一个 ProfileTracker 实例,该实例将开始跟踪配置文件更新,(即,当用户的配置文件完成获取时,将调用 ProfileTracker.onCurrentProfileChanged())。

以下是您需要登录 FB 并获取用户个人资料的完整代码:

LoginButton loginButton = (LoginButton) findViewById(R.id.btn_facebook);
loginButton.setReadPermissions("public_profile");
mCallbackManager = CallbackManager.Factory.create();
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {

    private ProfileTracker mProfileTracker;

    @Override
    public void onSuccess(LoginResult loginResult) {
        if(Profile.getCurrentProfile() == null) {
            mProfileTracker = new ProfileTracker() {
                @Override
                protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                    Log.v("facebook - profile", currentProfile.getFirstName());
                    mProfileTracker.stopTracking();
                }
            };
            // no need to call startTracking() on mProfileTracker
            // because it is called by its constructor, internally.
        }
        else {
            Profile profile = Profile.getCurrentProfile();
            Log.v("facebook - profile", profile.getFirstName());
        }
    }

    @Override
    public void onCancel() {
        Log.v("facebook - onCancel", "cancelled");
    }

    @Override
    public void onError(FacebookException e) {
        Log.v("facebook - onError", e.getMessage());
    }
});

您必须覆盖 Activity 或 Fragment 的 onActivityResult(),如下所示:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if you don't add following block,
    // your registered `FacebookCallback` won't be called
    if (mCallbackManager.onActivityResult(requestCode, resultCode, data)) {
        return;
    }
}

编辑:

代码更新为 Alex Zezekalo's suggestion仅在 Profile.getCurrentProfile() 返回 null 时调用 mProfileTracker.startTracking();

关于android - Profile.getCurrentProfile() 登录后返回 null (FB API v4.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29642759/

相关文章:

ios - 如何使用用户名链接到 iOS 应用程序中的 Facebook 用户?

android - 如何在 Android 中以编程方式获取 SharedPreferences 的所有键?

android - Android.mk 中的 aar 支持

android - 更改android对话框的背景颜色

ios - 我仅在使用 iOS Facebook 集成时获得 Facebook Active Access Token

facebook - 将网站点赞转移到粉丝专页点赞

java - 项目选择上带有微调器的弹出窗口不起作用

android - Android NDK 中与 Unix 域的 LocalSocket 通信

python - 谁分享了我的 Facebook 帖子?

ios - Facebook 分享 :- "An error occured.Please try again later" when sharing itunes link