Android Facebook session issue

2020-02-10 08:09发布

问题:

I have used following code for Facebook authentication and it is working fine, but when I have cancelled the authentication and tried to authenticate again the app crashed and the log was Caused by: java.lang.UnsupportedOperationException: Session: an attempt was made to open an already opened session.
On debug I got like this

{Session state:CREATED, token:{AccessToken token:ACCESS_TOKEN_REMOVED permissions:[]}, appId:xxxxxxxxxxxxxxx}

How can I solve this issue.Please help me.Thanks in advance

private void askFacebbokAuthentication() {

        Session session = Session.getActiveSession();
        if (session.isOpened()) {

            facebook = true;
            if (!hasPublishPermission()) {

                session.requestNewPublishPermissions(new NewPermissionsRequest(
                        MyActivity.this, PERMISSIONS));

            }
        } else {
            Session.OpenRequest openRequest = null;
            openRequest = new Session.OpenRequest(MyActivity.this);
            if (openRequest != null) {

                openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);

                if (!hasPublishPermission()) {
                    openRequest.setPermissions(PERMISSIONS);
                }
                session.openForPublish(openRequest);
            }
        }
    }

回答1:

I too had same problem, but i solved with these lines. To my knowledge we cannot request a session for new permissions which is already opened.

Session session = new Session(this);
    Session.setActiveSession(session);
    session.openForRead(new Session.OpenRequest(this).setCallback(callback).setPermissions(Arrays.asList("your_permissions")));

I hope you already added below line in onActivityResult()

Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);


回答2:

If the Session is neither opened nor closed, I think it is better to Session.openActiveSession()

This snipped is copied-pasted from the Facebook SDK sample project SessionLoginSample, LoginUsingActivityActivity#onClickLogin()

private void onClickLogin() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
    } else {
        Session.openActiveSession(this, true, statusCallback);
    }
}

Note that Session#openActiveSession() also creates a Session under the hood, which is OK. From https://developers.facebook.com/docs/technical-guides/iossdk/session/#lifecycle:

Sessions can only be opened once. When a session is closed, it cannot be re-opened. Instead, a new session should be created. Typical apps will only require one active session at any time. The Facebook SDK provides static active session methods that take care of opening new session instances.