11

我有以下活动,我正在使用 Facebook 的 LoginButton。onSessionStateChange 被多次调用。我有一个异步任务,我想在成功登录后运行它,一旦完成,它也会打开一个新活动。现在这会启动多个异步任务。我怎样才能找到最终状态,使其不会触发两次?我查看了所有示例,Facebook 说 session.isOpened() 应该可以工作,但它仍然会触发多次。

更新:

从 onResume 中删除会话代码后,它只会被调用一次,但根据https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/#step3我需要 OnResume 中的代码在某些情况下.

public class LoginActivity extends SherlockActivity {

private static final String TAG = "LoginActivity";

private Context context;
private int statusCode;
private String emailAddress = null;
private String password = null;
private GraphUser fbUser;

private UiLifecycleHelper uiHelper;

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
            Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    context = getApplicationContext();

    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

    final LoginButton fbBtn = (LoginButton) findViewById(R.id.facebook_login);
    fbBtn.setReadPermissions(Arrays.asList("basic_info", "email"));
    /*
     * fbBtn.setOnClickListener(new View.OnClickListener() {
     * 
     * @Override public void onClick(View v) {
     * 
     * Intent intent = new Intent(context, MainActivity.class);
     * startActivity(intent);
     * 
     * finish();
     * 
     * } });
     */
}

@Override
protected void onPause() {
    super.onPause();
    uiHelper.onPause();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
}

@Override
protected void onResume() {
    super.onResume();

    // For scenarios where the main activity is launched and user
    // session is not null, the session state change notification
    // may not be triggered. Trigger it if it's open/closed.
    Session session = Session.getActiveSession();
    if (session != null && (session.isOpened() || session.isClosed())) {
        onSessionStateChange(session, session.getState(), null);
    }
    uiHelper.onResume();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    uiHelper.onSaveInstanceState(outState);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("FbLogin", "Result Code is - " + resultCode +"");
    uiHelper.onActivityResult(requestCode, resultCode, data);

}

private void onSessionStateChange(Session session, SessionState state,
        Exception exception) {
    if (session != null && session.isOpened()) {
        Log.i(TAG, "Logged in...");
        Log.i(TAG, "Access Token" + session.getAccessToken());

        if (state == SessionState.OPENED) {
        Request.executeMeRequestAsync(session,
                new Request.GraphUserCallback() {
                    @Override
                    public void onCompleted(GraphUser user,
                            Response response) {
                        if (user != null) {
                            Log.i(TAG, "User ID " + user.getId());
                            Log.i(TAG, "Email " + user.asMap().get("email"));

                            fbUser = user;

                            //FbRegisterTask fbReg = new FbRegisterTask(LoginActivity.this, user);
                            //fbReg.execute();
                            //finish();
                        }
                    }
                });
        }

    } else if (session.isClosed()) {
        Log.i(TAG, "Logged out...");
    }
}
}
4

1 回答 1

23

我遇到过同样的问题。

一个调用来自 UiLifecycleHelper 调用回调时:

UiLifecycleHelper callback
onSessionStateChange()

另一个来自恢复 LoginFragment 的 Activity。

LoginActivity.onResumeFragments()
LoginFragment.onResume()
onSessionStateChange()

在许多情况下,这很好,但在您的情况下,这显然是由于 AsyncTask 造成的问题。

您可以缓存在 onSessionStateChange() 中收到的会话,并查看其状态和 tokenInfo 是否更改,然后才调用您的异步任务。检查会话状态和 tokenInfo 的组合就足够了:

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        if (mSession == null || isSessionChanged(session)) {
            mSession = session;
            LogUtils.LOGFB(TAG, "Logged in using facebook");
            LogUtils.LOGFB(TAG, "Access Token: " + session.getAccessToken());
            // Run your AsyncTask
        }

    } else if (state.isClosed()) {
        LogUtils.LOGFB(TAG, "Logged out from facebook");
        // Display your non-authenticated UI
    }
}

private boolean isSessionChanged(Session session) {

    // Check if session state changed
    if (mSession.getState() != session.getState())
        return true;

    // Check if accessToken changed
    if (mSession.getAccessToken() != null) {
        if (!mSession.getAccessToken().equals(session.getAccessToken()))
            return true;
    }
    else if (session.getAccessToken() != null) {
        return true;
    }

    // Nothing changed
    return false;
}
于 2013-12-31T00:14:26.997 回答