我正在使用我的Android应用程序登录Facebook。大多数情况下它工作正常,但有时代替OnSuccess方法调用LoginManager回调的OnCancel方法,在这种情况下,AccessToken.getCurrentAccessToken()也返回null。以下是我的登录活动的代码片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGson = new Gson();
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login--" + loginResult.getAccessToken());
accessToken = loginResult.getAccessToken();
getUserDetails();
}
@Override
public void onCancel() {
if(!NetUtils.isNetworkConnected(getApplicationContext())) {
Toast.makeText(FBLoginActivity.this, getString(R.string.error_msg_no_network),
Toast.LENGTH_SHORT).show();
} else {
accessToken = AccessToken.getCurrentAccessToken();
if(accessToken == null) {
Toast.makeText(FBLoginActivity.this, "Login unSuccessful..Please contact developer... ", Toast.LENGTH_LONG).show();
} else {
getUserDetails();
}
}
}
@Override
public void onError(FacebookException exception) {
accessToken = AccessToken.getCurrentAccessToken();
if(accessToken == null) {
Toast.makeText(FBLoginActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
} else {
getUserDetails();
}
}
});
// Ensure that our profile is up to date
// Profile.fetchProfileForCurrentAccessToken();
setContentView(R.layout.activity_login_fb);
mLayout = (RelativeLayout) findViewById(R.id.MainLayoutLogin);
fbLoginButton = (ImageView) findViewById(R.id.FBLoginButton);
fbLoginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(FBLoginActivity.this, Arrays.asList("public_profile, email, user_birthday"));
}
});
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(ApiEndPoints.BASE_URL)
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
mUserAPI = restAdapter.create(UserAPI.class);
}