如何在Facebook SDK中使用SharedPreferences?

时间:2016-10-19 23:18:11

标签: android facebook facebook-sdk-4.0 android-sharedpreferences

目前我的FB登录方式如下:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    TAG = "Login.Activity";

    //Callback manager manages callbacks into the FB SDK from an Activity's onActivityResult() Method.
    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.login_button);
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        //If login in successful,
        @Override
        public void onSuccess(LoginResult loginResult) {
            Profile profile = Profile.getCurrentProfile();
            goMainScreen(profile);
        }
        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(),R.string.cancel_login, Toast.LENGTH_LONG).show();
        }

        @Override
        public void onError(FacebookException error) {
            Toast.makeText(getApplicationContext(), R.string.error_login, Toast.LENGTH_LONG).show();
        }
    });
}
private void goMainScreen(Profile profile) {
    if(profile != null){
        //Passing in the name,id and photo from the profile.
        Intent intent = new Intent(this, MainActivity.class);
       // intent.putExtra("name",profile.getName());
        intent.putExtra("id",profile.getId());
        intent.putExtra("photo",profile.getProfilePictureUri(200,200));
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

@Override
//All Request Code, Result Code, and data are recieved by the activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode,resultCode,data);
    callbackManager.onActivityResult(requestCode,resultCode,data);
}
}

我想在其他活动中跟踪用户会话,并知道他们之前是否已登录。我是否应该使用共享偏好?如果是这样,我会在loginActivity的开头做这个吗?

1 个答案:

答案 0 :(得分:0)

您可以使用提供SDK的内容并创建类似这样的方法:

public boolean isLoggedIn() {
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    return accessToken != null;
}