12

我按照https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/的说明进行操作。当我触摸“登录”按钮时,会话状态始终为 OPENING。当我尝试将故事发布到用户的墙上时,我收到一条错误消息

“会话:尝试为具有待处理请求的会话请求新权限。”

这是我的代码:

public class MainFragment extends Fragment {
    private static final String TAG = "MainFragment";
    private UiLifecycleHelper uiHelper;

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

    private void onSessionStateChange(Session session, SessionState state,
            Exception exception) {
        if (state.isOpened()) {
            Log.d(TAG, "Logged in...");
        } else if (state.isClosed()) {
            Log.d(TAG, "Logged out...");
        } else {
            Log.d(TAG, "Unknown state: " + state);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        uiHelper = new UiLifecycleHelper(getActivity(), callback);
        uiHelper.onCreate(savedInstanceState);
    }

    @Override
    public 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 onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data);
    }

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

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

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.facebook_login, container, false);
        LoginButton authButton = (LoginButton) view
                .findViewById(R.id.authButton);
        authButton.setFragment(this);

        return view;
    }

    private boolean isSubsetOf(Collection<String> subset,
            Collection<String> superset) {
        for (String string : subset) {
            if (!superset.contains(string)) {
                return false;
            }
        }
        return true;
    }

    private static final List<String> PERMISSIONS = Arrays
            .asList("publish_actions");
    private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
    private boolean pendingPublishReauthorization = false;

    public void publishStory() {
        Session session = Session.getActiveSession();

        if (session != null) {

            // Check for publish permissions
            List<String> permissions = session.getPermissions();
            if (!isSubsetOf(PERMISSIONS, permissions)) {
                pendingPublishReauthorization = true;
                Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
                        this, PERMISSIONS);
                session.requestNewPublishPermissions(newPermissionsRequest);
                return;
            }

            Bundle postParams = new Bundle();
            postParams.putString("name", "Facebook SDK for Android");
            postParams.putString("caption",
                    "Build great social apps and get more installs.");
            postParams
                    .putString(
                            "description",
                            "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
            postParams.putString("link",
                    "https://developers.facebook.com/android");
            postParams
                    .putString("picture",
                            "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

            Request.Callback callback = new Request.Callback() {
                public void onCompleted(Response response) {
                    JSONObject graphResponse = response.getGraphObject()
                            .getInnerJSONObject();
                    String postId = null;
                    try {
                        postId = graphResponse.getString("id");
                    } catch (JSONException e) {
                        Log.i(TAG, "JSON error " + e.getMessage());
                    }
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        Toast.makeText(getActivity().getApplicationContext(),
                                error.getErrorMessage(), Toast.LENGTH_SHORT)
                                .show();
                    } else {
                        Toast.makeText(getActivity().getApplicationContext(),
                                postId, Toast.LENGTH_LONG).show();
                    }
                }
            };

            Request request = new Request(session, "me/feed", postParams,
                    HttpMethod.POST, callback);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
        }

    }
}

怎么了?

编辑:我还想提一下“登录”按钮上的文字不会改变。身份验证时我没有收到错误,但据我所知,它应该更改为“注销”。

4

9 回答 9

11

要弄清楚这一点并不容易。:-)

如果您真的签exceptiononSessionStateChange(),您会发现它并不是真的简单地卡在里面OPENING。该异常包含:java.lang.UnsupportedOperationException: Session: 试图打开一个有待处理请求的会话。

我终于找到的原因onActivityResult()是没有被调用。回调是它的责任,uiHelper并且该调用将调用登录的完成部分,因此如果不调用它,则状态将OPENING永远保持。除了上面明显的建议之外,这是我发现的,它们都是登录工作所必需的

确保您同时使用片段和活动,如 FB 文档中所述。即使文档暗示一项活动就足够了,但事实并非如此。即使活动除了调用单个片段之外什么都没有,您也需要两者。

确保您没有为活动设置历史记录(无论是在清单中还是在代码中)。

onActivityResult()确保按照文档覆盖片段。并确保在活动中也覆盖相同的内容:

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

是的,这看起来很奇怪,但没有它就行不通。

于 2014-01-24T22:44:05.457 回答
7

最后这对我有用。关键点是添加

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

        loginBtn.setFragment(this);
    loginBtn.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            graphUser = user;
        }
    });

片段内的代码:

private GraphUser graphUser;
private UiLifecycleHelper uiHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.test_frame, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    view.findViewById(R.id.getMeBtn).setOnClickListener(this);

    LoginButton loginBtn = (LoginButton) view.findViewById(R.id.loginBtn);
    loginBtn.setFragment(this);
    loginBtn.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
        @Override
        public void onUserInfoFetched(GraphUser user) {
            graphUser = user;
        }
    });
}

@Override
public void onResume() {
    super.onResume();
    uiHelper.onResume();

    updateUI();
}

@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);
    uiHelper.onActivityResult(requestCode, resultCode, data);
}

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

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

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

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    updateUI();
}

private void updateUI() {
    if (graphUser != null) {
        Log.d("TEST", graphUser.getFirstName());
    }
}

@Override
public void onClick(View view) {
    Session session = Session.getActiveSession();
    Log.d("TEST", "session.getState() = " + session.getState());

    if (session.getState().isOpened()) {
        Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

            @Override
            public void onCompleted(GraphUser user, Response response) {
                if (user != null) {
                    updateUI();
                }
            }
        });
    }
}
于 2013-05-01T04:09:02.420 回答
3

我遇到过同样的问题。状态总是OPENING. 事实证明@Gabor 是正确的。

当会话状态是OPENING一个方法onActivityResult被调用时,这是肯定的。

如果您使用的是片段,onActivityResult则在保存片段的 ACTIVITY 中调用,而不是在片段中。这是由于传递的上下文等。

所以我这样做了:

  1. 检查onActivityResults调用的内容(通过 logcat) - 只是为了确保

  2. 在该方法中添加一行Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);注意该参数this是一个活动上下文。



    使用UiLifecycleHelper'onActivityResult方法,如下所示: UiHelper.onActivityResult(requestCode, resultCode, data);更多信息请点击此处

于 2014-07-25T22:32:59.563 回答
2

如果其他人仍然遇到此问题,则可能是由于在 Activity 中覆盖 onActivityResult 而没有调用 super 方法。

活动

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    /* other code here */
    super.onActivityResult(requestCode, resultCode, data);
}

分段

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    uiHelper.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}
于 2013-11-29T10:42:02.743 回答
1

您应该onActivityResult在活动中而不是在片段中实现。为我工作。

于 2013-02-26T09:09:25.073 回答
1

这可能发生的另一个原因(对我来说)是当你使用时getChildFragmentManager()- onActivityResult 没有传递给嵌套的片段,因为 bug(让托管片段将其收到的 onActivityResult 传递给所有孩子)对我有帮助。

于 2014-07-17T09:26:50.793 回答
0

我的活动onActivityResult正在被调用......所以我在那里做了一个非常非常糟糕的黑客攻击:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 64206) //Bad hacking
            if(df!=null)
                df.onActivityResult(requestCode, resultCode, data);

df 是我的片段。这使得会议开始......这太疯狂了。非常有兴趣为此找到更好的解决方案。

于 2013-05-31T00:19:58.707 回答
0

就我而言,我试图将片段类从更改 android.support.v4.app.Fragmentandroid.app.Fragment(我不支持 API-11 之前的 Android 版本)并省略了该FBAuthButton.setFragment(this);语句。这实际上是造成问题的原因。

于 2015-05-04T18:44:50.497 回答
-1

我遇到了同样的问题,我卸载了我的应用程序并重新安装,它工作!

于 2013-04-25T15:54:06.370 回答