java.lang.UnsupportedOperationException:Session:尝试为具有挂起请求的会话请求新权限

时间:2013-02-09 14:03:13

标签: android facebook android-facebook

以下代码用于在android中使用facebookSDK3.0发布状态更新。如果我正在使用UiLifeCycleHelper类它运作良好。但我想在不使用UiLifeCycleHelper课程的情况下在Facebook上发布状态。我尝试了下面的代码,它在我的logcat中抛出错误,我的应用程序被强制关闭。

public class SampleFBPostActivity extends Activity implements OnClickListener {

private EditText mPostEditText;
private Button mDoneButton;
private Session mSession;
private PendingAction pendingAction = PendingAction.NONE;

private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private enum PendingAction {
    NONE,
    POST_STATUS_UPDATE
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fb_post);
    mPostEditText = (EditText) findViewById(R.id.post_text);
    mDoneButton = (Button) findViewById(R.id.done_button);
    mDoneButton.setOnClickListener(this);
    mSession = Session.getActiveSession();
    if (mSession == null) {
        mSession = new Session(this);
        Session.setActiveSession(mSession);
    }
    updateUI();
    handlePendingAction();
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.done_button:
        onClickPostStatusUpdate();
        break;
    }
}

 private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

 private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post, message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void onClickPostStatusUpdate() {
        performPublish(PendingAction.POST_STATUS_UPDATE);
    }

    private void postStatusUpdate(final String message) {
        if (mSession != null && hasPublishPermission()) {
            Request request = Request
                    .newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message, response.getGraphObject(), response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    private void performPublish(PendingAction action) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                handlePendingAction();
            } else {
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSIONS));
            }
        }
    }

private void updateUI() {
    Session session = Session.getActiveSession();
    boolean enableButtons = (session != null && session.isOpened());
    mDoneButton.setEnabled(enableButtons);
}

 private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {

            case POST_STATUS_UPDATE:
                postStatusUpdate(mPostEditText.getText().toString());
                break;
        }
    }
}

以下是logcat中的错误:

  02-09 14:00:36.126: E/AndroidRuntime(2396): java.lang.UnsupportedOperationException: Session: an attempt was made to request new permissions for a session that has a pending request.
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.facebook.Session.requestNewPermissions(Session.java:968)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.facebook.Session.requestNewPublishPermissions(Session.java:501)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.facebook.samples.sessionlogin.SampleFBPostActivity.performPublish(SampleFBPostActivity.java:113)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.facebook.samples.sessionlogin.SampleFBPostActivity.onClickPostStatusUpdate(SampleFBPostActivity.java:83)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.facebook.samples.sessionlogin.SampleFBPostActivity.onClick(SampleFBPostActivity.java:54)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.view.View.performClick(View.java:3511)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.view.View$PerformClick.run(View.java:14105)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.os.Handler.handleCallback(Handler.java:605)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.os.Handler.dispatchMessage(Handler.java:92)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.os.Looper.loop(Looper.java:137)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at android.app.ActivityThread.main(ActivityThread.java:4424)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at java.lang.reflect.Method.invokeNative(Native Method)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at java.lang.reflect.Method.invoke(Method.java:511)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  02-09 14:00:36.126: E/AndroidRuntime(2396):   at dalvik.system.NativeStart.main(Native Method)

请不要在解决方案中使用UiLifeCycleHelper课程来帮助我。提前致谢

2 个答案:

答案 0 :(得分:7)

您是否有特殊原因想要使用UiLifecycleHelper?该课程专门用于让您的生活更轻松,因此您不会遇到这样的问题。

如果必须,最简单的方法是查看UiLifecycleHelper中的代码,并将它们复制到Activity中的相应方法。

对于您的特定活动,我发现有两件事是错误的:

  1. 您无法随时打开会话(直接调用requestNewPublishPermissions,但您需要先打开会话)。调用“新会话”不会打开它。

  2. 您没有覆盖onActivityResult方法,这是将信息传递回活动会话所必需的。

答案 1 :(得分:0)

尝试以下代码。发布更新是最简单的示例:

在seeon登录后输入代码:

session.addCallback(new StatusCallback() {

    @Override
    public void call(Session session, SessionState state,
        Exception exception) {
        List<String> PERMISSIONS = Arrays
            .asList("publish_actions");
        session
            .requestNewPublishPermissions(new Session.NewPermissionsRequest(
                getActivity(), PERMISSIONS));

        Request request = Request.newStatusUpdateRequest(
            session, "Temple Hello Word Sample",
            new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    L.d("fb:done = "
                        + response.getGraphObject() + ","
                        + response.getError());
                }
            });
        request.executeAsync();

    }

});

以下是来自Facebook SDK3.0的示例会话登录的整个代码:

package com.facebook.samples.sessionlogin;

import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.microtemple.android.lib.common.L;

public class SessionLoginFragment extends Fragment {
    private static final String         URL_PREFIX_FRIENDS  = "https://graph.facebook.com/me/friends?access_token=";

    private TextView                    textInstructionsOrLink;
    private Button                      buttonLoginLogout;
    private final Session.StatusCallback    statusCallback      = new SessionStatusCallback();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment, container, false);

        buttonLoginLogout = (Button) view
            .findViewById(R.id.buttonLoginLogout);
        textInstructionsOrLink = (TextView) view
            .findViewById(R.id.instructionsOrLink);

        Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

        Session session = Session.getActiveSession();
        if (session == null) {
            if (savedInstanceState != null) {
                session = Session.restoreSession(getActivity(), null,
                    statusCallback, savedInstanceState);
            }
            if (session == null) {
                session = new Session(getActivity());
            }
            Session.setActiveSession(session);
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
            }
        }

        updateView();

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        Session.getActiveSession().addCallback(statusCallback);
    }

    @Override
    public void onStop() {
        super.onStop();
        Session.getActiveSession().removeCallback(statusCallback);
    }

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Session session = Session.getActiveSession();
        Session.saveSession(session, outState);
    }

    private void updateView() {
        Session session = Session.getActiveSession();
        if (session.isOpened()) {
            textInstructionsOrLink.setText(URL_PREFIX_FRIENDS
                + session.getAccessToken());
            buttonLoginLogout.setText(R.string.logout);
            buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickLogout();
                }
            });

            session.addCallback(new StatusCallback() {

                @Override
                public void call(Session session, SessionState state,
                    Exception exception) {
                    List<String> PERMISSIONS = Arrays
                        .asList("publish_actions");
                    session
                        .requestNewPublishPermissions(new Session.NewPermissionsRequest(
                            getActivity(), PERMISSIONS));

                    Request request = Request.newStatusUpdateRequest(
                        session, "getActiveSession",
                        new Request.Callback() {
                            @Override
                            public void onCompleted(Response response) {
                                L.d("fb:done = "
                                    + response.getGraphObject() + ","
                                    + response.getError());
                            }
                        });
                    request.executeAsync();

                }

            });


        } else {
            textInstructionsOrLink.setText(R.string.instructions);
            buttonLoginLogout.setText(R.string.login);
            buttonLoginLogout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickLogin();
                }
            });
        }
    }

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

    private void onClickLogout() {
        Session session = Session.getActiveSession();
        if (!session.isClosed()) {
            session.closeAndClearTokenInformation();
        }
    }

    private class SessionStatusCallback implements Session.StatusCallback {
        @Override
        public void call(Session session, SessionState state,
            Exception exception) {
            updateView();
        }
    }
}