1

com.facebook.widget.UserSettingsFragment用来管理登录/注销:

Fragment userSettingsFragment = new UserSettingsFragment();
fragmentTransaction.replace(R.id.content_container, userSettingsFragment, "userSettingsFragment");

然后在另一个Fragment我想在 Facebook 上发布一条消息。我检查了文档并写了MyFragment如下所示。

与 的连接com.facebook.widget.UserSettingsFragment似乎有效(我可以登录/注销),但是当我想在 中发布时MyFragment,似乎session.requestNewPublishPermissions(newPermissionsRequest);不会改变Session,因为onSessionStateChange从未调用过。

它调用一些FacebookUI 来请求许可,然后什么也没有发生。

我可以只com.facebook.widget.UserSettingsFragment用于登录/注销,即它是否管理所有 Facebook SDK 对象?我想知道,因为Session.getActiveSession();inMyFragment总是返回 a Session,即使我已注销。

有人可以帮忙吗?

public class MyFragment extends Fragment{

    private Button mBtnShare;

    private UiLifecycleHelper mUiHelper;

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

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

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (state.isOpened()) {
            if (pendingPublishReauthorization && 
                    state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
                pendingPublishReauthorization = false;
                publish();
            }
        } else if (state.isClosed()) {
        }
    }   

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (savedInstanceState != null) {
            pendingPublishReauthorization = 
                savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
        }

        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState){

        super.onActivityCreated(savedInstanceState);

        mBtnShare = (Button) getActivity().findViewById(R.id.btn_share);
        mBtnShare.setOnClickListener( new Button.OnClickListener() {  
            public void onClick(View v)
            {
               publish();
            }

        );
    }   


    @Override
    public void onCreate (Bundle savedInstanceState){

        super.onCreate(savedInstanceState);

        mUiHelper = new UiLifecycleHelper(getActivity(), mCallback);
        mUiHelper.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {     
        super.onResume();
        mUiHelper.onResume();
    }

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

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

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
        mUiHelper.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        super.onActivityResult(requestCode, resultCode, intent);
        mUiHelper.onActivityResult(requestCode, resultCode, intent);
    }   

    private void publish() {

        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(this.getClass().getSimpleName(), "JSON error "+ e.getMessage(), MyApplication.LOG_LEVEL);
                    }
                    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();
        }

    }

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

3 回答 3

1

我没有像示例代码中那样检查每个请求的权限,而是直接在com.facebook.widget.UserSettingsFragment

UserSettingsFragment userSettingsFragment = new UserSettingsFragment();                 
Session session = Session.getActiveSession();
if(session==null || session.isClosed()){
    userSettingsFragment.setPublishPermissions(Arrays.asList("publish_actions"));
}
fragmentTransaction.replace(R.id.content_container, userSettingsFragment, "userSettingsFragment");
于 2013-08-17T10:26:36.230 回答
0

您的代码似乎与 Facebook 上的 feed 教程相同,我找不到区别。在您看到 Facebook UI 弹出权限后,可能UiLifecycleHelper不会调用call方法。StatusCallback

只是为了验证,添加session.addCallback(mCallback);

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

然后,调试并检查是否onSessionStateChange被调用。如果它被调用了,不要离开这一行,而是检查你的 logcat 或调试UiLifecycleHelper它为什么没有call()调用StatusCallback. 如果它没有被调用,那么可能你有权限或登录问题。

除了这些检查,您还可以使用这个android-simple-facebook库:https ://github.com/sromku/android-simple-facebook

您可以轻松登录/注销发布提要/照片等,而无需进行任何痛苦的编码。除了简单的示例之外,还有一个示例应用程序,带有片段的示例。

登录示例:

mSimpleFacebook.login(onLoginListener);

发布提要示例:

Feed feed = new Feed.Builder()
           .setMessage("Clone it out...")
           .setName("Simple Facebook for Android")
           .setCaption("Code less, do the same.")
           .setDescription("The Simple Facebook library project makes the life much easier by coding less code for being able to login, publish feeds and open graph stories, invite friends and more.")
           .setPicture("https://raw.github.com/sromku/android-simple-facebook/master/Refs/android_facebook_sdk_logo.png")
           .setLink("https://github.com/sromku/android-simple-facebook")
           .build();

// publish the feed
mSimpleFacebook.publish(feed, onPublishListener);

而且,不需要关心询问READ 和 PUBLISH 权限的正确顺序。您可以设置您打算在您的应用程序中使用的所有权限,该库将在连接时触发 Facebook 权限对话框一个接一个,或者如果您在对话框中拒绝 PUBLISH 权限,它将再次触发发布操作对话框

于 2013-09-08T08:05:14.730 回答
0

Facebook Login only works for single activity of your application. You need mention the activity name and package name while your creating facebook appid. So Finally Facebook authentication and posting only works for specified activity.

于 2013-08-17T07:05:24.123 回答