在Android Facebook SDK中使用共享对话框。如何知道用户实际共享或取消共享活动?

时间:2013-11-02 19:43:10

标签: android facebook facebook-android-sdk android-facebook

我已按照此处https://developers.facebook.com/docs/android/share-dialog/#setup

所述向Android应用添加了共享功能

但我注意到,如果用户被取消,则无论如何都要调用共享活动onComplete

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

    uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.e("Activity", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.e("Activity", "Success!");
        }
    });
}

我也查看了返回的Bundle。即使我取消分享对话我也

com.facebook.platform.extra.DID_COMPLETE=true

如何获得用户真正在Facebook上共享数据的结果? (不用facebook按钮单独登录。也许需要添加一些权限?)

6 个答案:

答案 0 :(得分:7)

请参阅https://developers.facebook.com/docs/android/share-dialog/#handling-responses

您可以通过调用

来判断用户是否已取消
String gesture = FacebookDialog.getNativeDialogCompletionGesture(data);
if (gesture != null) {
  if ("post".equals(gesture)) {
    // the user hit Post
  } else if ("cancel".equals(gesture)) {
    // the user hit cancel
  } else {
    // unknown value
  }
} else {
  // either an error occurred, or your app has never been authorized
}

其中data是结果包。但是,如果用户通过您的应用程序登录(即您至少具有basic_info权限),它将仅返回非空值。如果用户从未登录或授权您的应用程序,那么您将看到的唯一内容是DID_COMPLETE,除非发生错误,否则它将始终为true。这是设计的。

答案 1 :(得分:5)

为了获得共享的结果,您的应用至少需要具有basic_info权限。

要解决这个问题,只需打开一个会话(这将自动请求basic_info权限):

Session.openActiveSession(this /*your activity*/, 
                          true /*allows the UI login to show up if needed*/, 
                          new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        Log.i("[Facebook]", "Session: " + state.toString());
        if (session.isOpened()) {
           /// now you are good to get the sharing results
        }
    }
});

您可以在此处找到更多信息:https://developers.facebook.com/docs/android/getting-started/

答案 2 :(得分:3)

@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
    if (data.getString("com.facebook.platform.extra.COMPLETION_GESTURE").equals("cancel"))
        return;
}

data.getString("com.facebook.platform.extra.COMPLETION_GESTURE")的值为" post"当用户在Facebook上发帖时。

答案 3 :(得分:3)

实施FacebookCallback<Sharer.Result>以了解共享是成功还是取消,或者是否有错误。

您也可以在Activity和Fragment中使用以下代码。在Fragment中使用时,请确保在ShareDialog构造函数中传递this。如果您通过getActivity(),则不会在片段中触发onActivityResult方法。

private CallbackManager callbackManager;

private void shareYourContentOnFacebook() {

    callbackManager = CallbackManager.Factory.create();
    ShareDialog shareDialog = new ShareDialog(this);
    shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
        @Override
        public void onSuccess(Sharer.Result result) {
            Log.d(this.getClass().getSimpleName(), "shared successfully");
            //add your code to handle successful sharing
        }

        @Override
        public void onCancel() {
            Log.d(this.getClass().getSimpleName(), "sharing cancelled");
            //add your code to handle cancelled sharing

        }

        @Override
        public void onError(FacebookException error) {
            Log.d(this.getClass().getSimpleName(), "sharing error");
            //add your code to handle sharing error

        }
    });

    if (ShareDialog.canShow(ShareLinkContent.class)) {

        ShareLinkContent shareLinkContent = new ShareLinkContent.Builder()
                .setContentTitle("Your content title")
                .setContentDescription("Your content description")
                .setContentUrl(Uri.parse(""http://your-content-url.com""))
                .build();

        shareDialog.show(shareLinkContent);

    }

}

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

答案 4 :(得分:1)

使用此代码: -

/**
 * Facebook Dialog Callback 
 * 
 * Called up when come back from Share Dialog
 * 
 */
private class FacebookDialogCallBack implements FacebookDialog.Callback
{
    @Override
    public void onComplete(PendingCall pendingCall, Bundle data) 
    {
        //Show Toast Message
        showToastMessage(data);
    }

    @Override
    public void onError(PendingCall pendingCall, Exception error, Bundle data) 
    {
        //Show Toast Message
        showToastMessage(data);
    }
}
//Show Toast Message
private void showToastMessage(Bundle data)
{
    //Get Native Dialog Did Complete
    boolean didComplete = FacebookDialog.getNativeDialogDidComplete(data);

    if(didComplete)
    {
        //Get Native Dialog Completion Gesture
        String nativeDialogCompletionGesture = FacebookDialog.getNativeDialogCompletionGesture(data);

        if (nativeDialogCompletionGesture == null || FacebookDialog.COMPLETION_GESTURE_CANCEL.equals(nativeDialogCompletionGesture))
        {
            //Show Publish Cancel Toast
            UIUtil.showToast(R.string.toast_message_share_publish_cancelled);                                               
        }
        else
        {
            //Show Success Post Toast
            UIUtil.showToast(R.string.toast_message_share_success_post);
        }
    }
    else
    {
        //Show Publish Cancel Toast
        UIUtil.showToast(R.string.toast_message_share_publish_cancelled);
    }
}

答案 5 :(得分:1)

Heading ## private static ShareDialog shareDialog;

    private static FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
        @Override
        public void onCancel() {
            Log.d("HelloFacebook", "Canceled");
        }

        @Override
        public void onError(FacebookException error) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
            String title = this.getActivty().getString(R.string.error);
            String alertMessage = error.getMessage();
            showResult(title, alertMessage);
        }

        @Override
        public void onSuccess(Sharer.Result result) {
            Log.d("HelloFacebook", "Success!");
            // 不为空,才分享成功
            if (result.getPostId() != null) {
                String title = this.getActivty().getString(R.string.success);
                String id = result.getPostId();
                String alertMessage = this.getActivty().getString(R.string.successfully_posted_post, id);
                showResult(title, alertMessage);
            }
        }

        private void showResult(String title, String alertMessage) {
            new AlertDialog.Builder(this.getActivty())
                    .setTitle(title)
                    .setMessage(alertMessage)
                    .setPositiveButton(R.string.ok, null)
                    .show();
        }
    };

protected void onCreate (Bundle savedInstanceState)
{
             shareDialog = new ShareDialog(this. getActivty());
             shareDialog.registerCallback( callbackManager, shareCallback);
}