应用重启后 Facebook 访问令牌丢失

Facebook Access Token lost after App Restart

我正在使用 Facebook SDK 4.0 并使用内置的登录按钮。 我有一个包含 LoginButton 的 Fragment 和另一个只包含一个 TextBox 的

这是来自 Fragment 的代码片段:

public class LoginFragment extends Fragment {

private OnLoginFragmentInteractionListener mListener;
LoginButton loginButton;
CallbackManager callbackManager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
    }

    callbackManager = CallbackManager.Factory.create();
}

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

    loginButton = (LoginButton) view.findViewById(R.id.login_button);

    // If using in a fragment
    loginButton.setFragment(this);

    // Callback registration
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Toast.makeText(getActivity(), "Logged in successfully.", Toast.LENGTH_SHORT).show();
            onLoginEvent(true);
        }
        @Override
        public void onCancel() {
            Toast.makeText(getActivity(), "Login canceled.", Toast.LENGTH_SHORT).show();
            onLoginEvent(false);
        }
        @Override
        public void onError(FacebookException exception) {
            Toast.makeText(getActivity(), "Failed to log in. Please try again.", Toast.LENGTH_SHORT).show();
            onLoginEvent(false);
        }
    });

    return view;
}

public void onLoginEvent(boolean loginSuccess) {
    if (mListener != null) {
        mListener.onLoginFragmentInteraction(loginSuccess);
    }
}

public interface OnLoginFragmentInteractionListener {
    public void onLoginFragmentInteraction(boolean onLoginSuccess);
}

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

Activity 看起来像这样:

public class LoginActivity extends ActionBarActivity implements
    LoginFragment.OnLoginFragmentInteractionListener, TestFragment.OnFragmentInteractionListener {

static final String TAG = "LoginActivity";

private LoginFragment loginFragment;
private TestFragment testFragment;
private AccessToken accessToken;
private AccessTokenTracker accessTokenTracker;
private Profile fbProfile;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    FacebookSdk.sdkInitialize(getApplicationContext());

    if (savedInstanceState == null) {
        // Add the fragment on initial activity setup
        Log.d(TAG, "Bundle = null, isLoggedIn() = " + isLoggedIn());
        if (isLoggedIn()) {
            testFragment = new TestFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, testFragment).commit();
        } else {
            loginFragment = new LoginFragment();
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, loginFragment).commit();
        }
    } else {
        // Or set the fragment from restored state info
        Fragment frag = getSupportFragmentManager()
                .findFragmentById(R.id.fragment_container);
        if (frag instanceof LoginFragment) {
            Log.d(TAG, "Bundle != null, fragment = LoginFragment");
            loginFragment = (LoginFragment) frag;
        }
        else if (frag instanceof TestFragment) {
            Log.d(TAG, "Bundle != null, fragment = TestFragment");
            testFragment = (TestFragment) frag;
        }
    }
}


@Override
public void onLoginFragmentInteraction(boolean loginSuccess) {
    updateUI(loginSuccess);
}

public void updateUI(boolean loggedIn) {
    // User is logged in, show the main fragment
    if (loggedIn) {
        testFragment = new TestFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, testFragment).commit();
    }
    // User is logged out, show the login fragment
    else {
        loginFragment = new LoginFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, loginFragment).commit();
    }
}

public boolean isLoggedIn() {
    accessToken = AccessToken.getCurrentAccessToken();
    if (accessToken != null && !accessToken.isExpired())
        return true;
    else
        return false;
}
}

我想做的是检查用户是否已经登录。如果已经登录,则显示测试片段,否则显示登录片段。

所以当用户第一次登录时,我使用接口回调通知Activity用户已经登录,并显示TestFragment。此外,如果用户离开应用程序然后 returns,如果用户通过检查访问令牌登录,我会检查 onCreate() 方法。

当用户首次登录时,它会按预期工作。 但我面临的问题是,如果我终止该应用程序或将其从“最近”列表中删除,我将丢失访问令牌。 AccessToken.getCurrentAccessToken() 始终 returns 为空。 这不是正确的处理方式吗?

登录成功后将访问令牌保存在某处。到数据库或共享首选项。当您的应用启动时检查是否有访问令牌以及是否有效。

正如您在评论中提到的那样。当 FacebookSDK 完成初始化时,您应该检查用户登录。
您的问题是您在 SDK 尚未完成初始化时检查了 AccessToken。为解决此问题,请在 FacebookSdk.InitializeCallback 的 onInitialized() 方法中检查 AcessToken,该方法在 SDK 初始化时调用。

FacebookSdk.sdkInitialize(getApplicationContext(), new FacebookSdk.InitializeCallback() {
    @Override
    public void onInitialized() {
        if (isLoggedIn()) {
            ..............
        }
    }
});