简体   繁体   English

Facebook Android SDK 3.0,如何在没有LoginButton的情况下共享内容

[英]Facebook Android SDK 3.0, how to share content without the LoginButton

I am now doing a little project that want to have a share button(dialog), when users click it, it will auto-login to his/her fb account and share the content they want. 我现在正在做一个想要拥有共享按钮(对话框)的小项目,当用户点击它时,它将自动登录到他/她的fb帐户并共享他们想要的内容。

After the tutorial from fb dev, my app can share content to wall, but need to login with a fblogin button before sharing. 在fb dev的教程之后,我的应用程序可以将内容共享到墙上,但需要在共享之前使用fblogin按钮登录。

I have read a post from stackoverflow: Android - Facebook SDK 3 - How to login programmatically without LoginButton 我已经阅读了stackoverflow的帖子: Android - Facebook SDK 3 - 如何在没有LoginButton的情况下以编程方式登录

UPDATE : I have implement the feedDialog with onActivityResult in my project, I found that i can login and share with one button. 更新 :我在项目中使用onActivityResult实现了feedDialog,我发现我可以用一个按钮登录和共享。 HOWEVER , when i rebuild the app/restart my phone, i have to press the button twice to share at the first time , but become normal(press once) later. 但是 ,当我重建应用程序/重新启动手机时, 我必须按两次按钮才能在第一时间共享 ,但稍后会变为正常(按一次)。

PSI have implement it with shareActionProvider PSI使用shareActionProvider实现它

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getSupportMenuInflater().inflate(R.menu.content_main, menu);
    /** Getting the actionprovider associated with the menu item whose id is share */
    mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();

    /** Getting the target intent */
    Intent intent = getDefaultShareIntent();

    /** Setting a share intent */       
    if(intent!=null){
        mShareActionProvider.setShareIntent(intent);
        mShareActionProvider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener(){
            @Override
            public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
                if ("com.facebook.katana".equals(intent.getComponent().getPackageName())){
                    if (Session.getActiveSession() == null || Session.getActiveSession().isClosed()) {
                        Session.openActiveSession(Content.this, true, null);
                }else{
                        publishFeedDialog();
                    }
                    return true;
                }
                return false;
            }
        });
    }

    return super.onCreateOptionsMenu(menu);
}
@Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        if (Session.getActiveSession() != null || Session.getActiveSession().isOpened())
            publishFeedDialog();
    }
private void publishFeedDialog() {
        Bundle params = new Bundle();
        params.putString("name", "ab");
        params.putString("caption", "cd");
        params.putString("description", "def");
        params.putString("link", "https://developers.facebook.com/android");
        params.putString("picture", "abc.jpg");

        WebDialog feedDialog = (
            new WebDialog.FeedDialogBuilder(Content.this,
                Session.getActiveSession(),
                params))
            .setOnCompleteListener(new OnCompleteListener() {

                @Override
                public void onComplete(Bundle values,
                    FacebookException error) {
                    if (error == null) {
                        // When the story is posted, echo the success
                        // and the post Id.
                        final String postId = values.getString("post_id");
                        if (postId != null) {
                            Toast.makeText(Content.this,
                                "Posted story, id: "+postId,
                                Toast.LENGTH_SHORT).show();
                        } else {
                            // User clicked the Cancel button
                            Toast.makeText(Content.this.getApplicationContext(), 
                                "Publish cancelled", 
                                Toast.LENGTH_SHORT).show();
                        }
                    } else if (error instanceof FacebookOperationCanceledException) {
                        // User clicked the "x" button
                        Toast.makeText(Content.this.getApplicationContext(), 
                            "Publish cancelled", 
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // Generic, ex: network error
                        Toast.makeText(Content.this.getApplicationContext(), 
                            "Error posting story", 
                            Toast.LENGTH_SHORT).show();
                    }
                }

            })
            .build();
        feedDialog.show();
        }

Thanks Ming Li very much for the solution 非常感谢Ming Li的解决方案

I finally got the answer!!!! 我终于得到了答案!!!! Below is the code, hope that it can help other developers 下面是代码,希望它可以帮助其他开发人员

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()) {
            publishFeedDialog();
        }
    }
    //........................
                    if (Session.getActiveSession() == null || Session.getActiveSession().isClosed()) {
                            Session.openActiveSession(Content.this, true, callback);
                    }else{
                            publishFeedDialog();
                        }
     //.......................
    @Override
       public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
        }
    private void publishFeedDialog() {
            //........................
      }

I think the issue here is that when you're building the menu, you check to see if the active session is null, and if it is, you call openActiveSession, and wait for onActivityResult to be called. 我认为这里的问题是,当您构建菜单时,检查活动会话是否为空,如果是,则调用openActiveSession,并等待onActivityResult被调用。

This is all correct, HOWEVER, if the user has previously authorized your app, then the access tokens, etc, are all saved in a token cache, and calling openActiveSession will actually open the session immediately (without calling onActivityResult). 这是正确的,但是,如果用户先前已经授权您的应用程序,那么访问令牌等都保存在令牌缓存中,并且调用openActiveSession将实际立即打开会话(不调用onActivityResult)。

The real correct way is to pass in a StatusCallback to your open call (rather than null), and in that call back, check to see if the session is open, and call your publishFeedDialog method. 真正正确的方法是将StatusCallback传递给您的打开调用(而不是null),并在该回调中,检查会话是否打开,并调用您的publishFeedDialog方法。

This is covered right in the Getting Started tutorial: 这在“ Getting Started教程中有所介绍:

    package com.firstandroidapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;
import com.facebook.*;
import com.facebook.model.*;

public class MainActivity extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

// start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {

  // callback when session changes state
  @Override
  public void call(Session session, SessionState state, Exception exception) {
    if (session.isOpened()) {

      // make request to the /me API
      Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

        // callback after Graph API response with user object
        @Override
        public void onCompleted(GraphUser user, Response response) {
          if (user != null) {
            TextView welcome = (TextView) findViewById(R.id.welcome);
            welcome.setText("Hello " + user.getName() + "!");
          }
        }
      });
    }


     }
    });
  }

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

}

LoginButton in facebook-sdk-3.0 is just a tool for get a session from FB. facebook-sdk-3.0中的LoginButton只是一个从FB获取会话的工具。

If you already get a session from FB, you need to check a permission to publish. 如果您已经从FB获得会话,则需要检查发布权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM