Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何以编程方式共享Android中的FB状态_Android_Facebook - Fatal编程技术网

如何以编程方式共享Android中的FB状态

如何以编程方式共享Android中的FB状态,android,facebook,Android,Facebook,我想通过编程在facebook上共享我的应用程序中的文本/图像。我应该如何继续。在谷歌搜索了很多之后,我发现了很多示例应用程序,但由于最新的FB SDK不推荐使用这些API,因此很难找到使用新SDK的方法。请帮助我解决这个问题 private void publishFeedDialog() { Bundle params = new Bundle(); params.putString("name", "Facebook SDK for Android");

我想通过编程在facebook上共享我的应用程序中的文本/图像。我应该如何继续。在谷歌搜索了很多之后,我发现了很多示例应用程序,但由于最新的FB SDK不推荐使用这些API,因此很难找到使用新SDK的方法。请帮助我解决这个问题

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

    WebDialog feedDialog = (
        new WebDialog.FeedDialogBuilder(getApplicationContext(),
            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(getApplicationContext(),
                            "Posted story, id: "+postId,
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(getApplicationContext(), 
                            "Publish cancelled", 
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(getApplicationContext(), 
                        "Publish cancelled", 
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(getApplicationContext(), 
                        "Error posting story", 
                        Toast.LENGTH_SHORT).show();
                }
            }

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

这就是我从fb API 3.5 doc中得到的信息&我已经尝试过了,但它说会话为空,这会使应用程序崩溃。

这里您的会话为空,因为您尚未启动它。 您必须在登录后启动会话

您可以通过使用

Session.openActiveSession(this, true, new Session.StatusCallback() {

  // callback when session changes state

});
有关更多信息,请尝试阅读中的教程。这些真的很有帮助

下面是我如何实现的--

这个类用于对facebook进行初始操作

LoginFacebookClass

/**
* for integrating facebook in your app..
* Firstly import FacebookSDK lib project and add in your project as lib project.
* then 
*  create an instance of this class
* and, then call the facebook login method by passing reference of your activity and   true, if you want to fetch data and, false if you want to share data on faceboko
* Please do whatever you want in the interface callback methods 
* implemented by this class
 * 
 * 
 * Note: Please write a line exactly in your activity's on activity result as
 * -- Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
 * here, 'Session' is Class of Facebook.
 * 'this' is reference of your activity

*/
 public class FacebookLoginClass implements FB_Callback
 {
  Context context;
 FBImPlmentation fbImpl;
String mImageURLString = "", mPhotoTypeString = "";
 // private FBBean userDataBean;

/**
 * constructor for FacebookLoginClass
 * @param con : context of activity
 * @param string 
 * @param mImageURLString2 
 */
public FacebookLoginClass(Context con)
{
    this.context = con;
    fbImpl = FBImPlmentation.getInstance(context, this);
}

public FacebookLoginClass(Context con, String imageURLString, String photoType) 
{
    this.context = con;
    fbImpl = FBImPlmentation.getInstance(context, this);
    mImageURLString = imageURLString;
    mPhotoTypeString = photoType;
}

/**
 * method for initiating facebook Login
 * @param isDataFetch : true for fetching user data, false for sharing on wall
 */
public void facebookLogin(boolean isDataFetch)
{
    fbImpl.CheckSession(isDataFetch);
}

/**
 * method for facebookLogout 
 */
public void facebookLogout()
{
    fbImpl.fbLogout();
}

@Override
public void onLogin(Session s)
{
    fbImpl.getDataFromFB(s);
}

@Override
public void onLoginForShareData()
{
    Log.e("facebook.", "True in..........");
    Bundle postParams = new Bundle();
    postParams.putString("name", "");
    postParams.putString("caption", "");
    postParams.putString("description", " Android, share your pics and videos");
    if (mPhotoTypeString.equalsIgnoreCase("photo")) 
    {
        postParams.putString("picture", mImageURLString);
    } 
    else 
    {
        postParams.putString("link", "");
    }
    fbImpl.publishFeedDialog(postParams);
}

@Override
public void onAuthFailiure()
{

}

@Override
public void onUserData(FBBean fbUserDataBean)
{
    try 
    {
        if (BejoelUtility.isNetworkAvailable(context)) 
        {
            String imageURLString = "http://graph.facebook.com/" + fbUserDataBean.getUserID() + "/picture?type=large";
            new FacebookTwitterLoginAsyncTask(context, fbUserDataBean.getFirstNAme(), fbUserDataBean.getLastName(),
                    fbUserDataBean.getMailId(), fbUserDataBean.getUserBday(), fbUserDataBean.getUserSex(), "", "", imageURLString,
                    fbUserDataBean.getAccessToken(), "facebook").execute();
        } 
        else 
        {
            BejoelUtility.showMsgDialog(context, context.getString(R.string.app_name), context.getString(R.string.no_internet));
        }
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

@Override
public void onPost(boolean postStatus)
{
    // TODO Auto-generated method stub

}

@Override
public void onFriendRequest(boolean shareAppStatus)
{
    // TODO Auto-generated method stub

}

@Override
public void onLogout(boolean status)
{
    // TODO Auto-generated method stub

}

}
该课程与facebook互动

public class FBImPlmentation
{
public static List<String> READ_PERMISSIONS = Arrays.asList("email");
public List<String> WRITE_PERMISSIONS = Arrays.asList("publish_actions");
private static FBImPlmentation fbImpl;
private FB_Callback mInterface;
private static Activity activity;
boolean isDataFetch=false;
private String mAccessTokenString = "";

/**
 * constructor for facebookImplementation
 * @param con :context of activity via FacebookLogin Class
 * @param mInterface : refrence of class implementing FB_Callback interface..as in our case,
 *  it is refrence of FacebookLogin Class
 * @return : instance of FBImplementation
 */
public static FBImPlmentation getInstance(Context con, FB_Callback mInterface)
{
    activity = (Activity) con;
    if (fbImpl == null)
        fbImpl = new FBImPlmentation();
    fbImpl.mInterface = mInterface;
    return fbImpl;
}

/**
 * method to be called for facebook Logout
 */
public void fbLogout()
{
    if (Session.getActiveSession() != null)
    {
        Session.getActiveSession().closeAndClearTokenInformation();
    }
    Session.setActiveSession(null);
    mInterface.onLogout(true);
}

/**
 * method for checking session.
 * if session is not open, then open a new session.
 * If session is already open then..just call the fbcallback onlogin method
 * @param isDataFetch2 
 */
public void CheckSession(boolean isDataFetch2)
{
    fbImpl.isDataFetch= isDataFetch2;
    Session s = Session.getActiveSession();
    if (s != null && s.isOpened())
    {
        if(isDataFetch)
            mInterface.onLogin(s);
        else
            mInterface.onLoginForShareData();
        mAccessTokenString = s.getAccessToken();
    }
    else
    {
        Session.openActiveSession(activity, true, mFBCallback);
    }
}

//  Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, permissions);
Session.StatusCallback mFBCallback = new Session.StatusCallback()
{
    // call method is always called on session state change
    @Override
    public void call(Session session, SessionState state, Exception exception)
    {
        if (session.isOpened())
        {
            List<String> permissions = session.getPermissions();
            if (!isSubsetOf(READ_PERMISSIONS, permissions))
            {
                Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity, READ_PERMISSIONS);
                session.requestNewReadPermissions(newPermissionsRequest);
                return;
            }
            else if(isDataFetch)
            {
                mInterface.onLogin(session);
            }
            else
            {
                mInterface.onLoginForShareData();
            }

        }
    }
};

/**
 * method for fetching the user data
 * @param session : it takes the refrence of active session
 */
public void getDataFromFB(Session session)
{
    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)
            {
                // code to retrieve user's data and pass to signup fragment
                FBBean fbUserDataBean = new FBBean();

                if (mAccessTokenString != null)
                    fbUserDataBean.setAccessToken(mAccessTokenString);
                else 
                {
                    fbUserDataBean.setAccessToken("");
                }

                if (user.getUsername() != null && !(user.getUsername().equals(null)))
                    fbUserDataBean.setUserName(user.getUsername());
                else 
                {
                    fbUserDataBean.setUserName("");
                }

                if (user.getFirstName() != null && !(user.getFirstName().equals(null)))
                    fbUserDataBean.setFirstNAme(user.getFirstName());
                else 
                {
                    fbUserDataBean.setFirstNAme("");
                }

                if (user.getLastName() != null && !(user.getLastName().equals(null)))
                    fbUserDataBean.setLastName(user.getLastName());
                else 
                {
                    fbUserDataBean.setLastName("");
                }

                if (user.getBirthday() != null && !(user.getBirthday().equals(null)))
                    fbUserDataBean.setUserBday(user.getBirthday());
                else 
                {
                    fbUserDataBean.setUserBday("");
                }

                if (user.asMap().get("gender") != null) 
                {
                    fbUserDataBean.setUserSex(user.asMap().get("gender").toString());
                }
                else 
                {
                    fbUserDataBean.setUserSex("");
                }

                if (user.getProperty("email") != null && !(user.getProperty("email").equals(null)))
                    fbUserDataBean.setMailId(user.getProperty("email").toString());
                else 
                {
                    fbUserDataBean.setMailId("");
                }

                if (user.getId() != null && !(user.getId().equals(null)))
                    fbUserDataBean.setUserID(user.getId());
                else 
                {
                    fbUserDataBean.setUserID("");
                }

//        String[] sportsArray = FacebookUtils.getSportsArray(user.getInnerJSONObject());
//                  if (sportsArray != null &&    !(sportsArray.equals(null)))
  //                        fbUserDataBean.setSportsname(sportsArray);

                mInterface.onUserData(fbUserDataBean);
             }
        }
    });
}

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

/**
 * method for publishing posts
 */
public void publishFeedDialog(Bundle postParams)
{
    Session s = Session.getActiveSession();
    List<String> permissions = s.getPermissions();
    if (!isSubsetOf(WRITE_PERMISSIONS, permissions))
    {
        Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(activity,
                WRITE_PERMISSIONS);
        s.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", "Video by Lata manadjahgkfdjhaskjd akhgfkjashfkjash");
   //       postParams.putString("link", "");
    //        postParams.putString("picture", "");

    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, Session.getActiveSession(), postParams))
            .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)
                        {
                            mInterface.onPost(true);
                        }
                        else
                        {
                            // User clicked the Cancel button
                            mInterface.onPost(false);
                        }
                    }
                    else
                        if (error instanceof FacebookOperationCanceledException)
                        {
                            // User clicked the "x" button
                            //                              Toast.makeText(MainActivity.this.getApplicationContext(), "Publish cancelled",
                            //                                      Toast.LENGTH_SHORT).show();
                            mInterface.onPost(false);
                        }
                        else
                        {
                            // Generic, ex: network error
                            //                              Toast.makeText(MainActivity.this.getApplicationContext(), "Error posting story",
                            //                                      Toast.LENGTH_SHORT).show();
                            mInterface.onAuthFailiure();
                        }
                }

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

}
公共类FBI实现
{
public static List READ_PERMISSIONS=Arrays.asList(“电子邮件”);
public List WRITE_PERMISSIONS=Arrays.asList(“发布_操作”);
专用静态FBIMPLE FBIMPLE;
私人FB_回调mInterface;
私人静态活动;
布尔值isDataFetch=false;
私有字符串mAccessTokenString=“”;
/**
*FaceBook实现的构造函数
*@param con:通过FacebookLogin类的活动上下文
*@param mInterface:引用类实现FB_回调接口..就像我们的例子一样,
*这是FacebookLogin类的引用
*@return:fbi实现实例
*/
公共静态FBImplementation getInstance(上下文con,FB_回调mInterface)
{
活动=(活动)con;
如果(fbImpl==null)
fImpl=新的fImplementation();
fimpl.mInterface=mInterface;
返回fbImpl;
}
/**
*要为facebook注销调用的方法
*/
公共注销()
{
if(Session.getActiveSession()!=null)
{
Session.getActiveSession().closeAndClearTokenInformation();
}
Session.setActiveSession(null);
mInterface.onLogout(true);
}
/**
*用于检查会话的方法。
*如果会话未打开,则打开一个新会话。
*如果会话已打开,则..只需调用fbcallback onlogin方法
*@param isDataFetch2
*/
公共无效检查会话(布尔值isDataFetch2)
{
fImpl.isDataFetch=isDataFetch2;
会话s=Session.getActiveSession();
如果(s!=null&&s.isOpened())
{
if(isDataFetch)
mInterface.onLogin(s);
其他的
mInterface.onLoginForShareData();
MacAccessTokenString=s.getAccessToken();
}
其他的
{
openActiveSession(activity,true,mFBCallback);
}
}
//Session.newpermissions请求newpermissions请求=新建会话。newpermissions请求(活动、权限);
Session.StatusCallback mFBCallback=新建Session.StatusCallback()
{
//会话状态更改时始终调用call方法
@凌驾
公共无效调用(会话、会话状态、异常)
{
if(session.isOpened())
{
List permissions=session.getPermissions();
如果(!isSubsetOf(读取权限、权限))
{
Session.newpermissions请求newpermissions请求=新会话.newpermissions请求(活动,读取权限);
session.requestNewReadPermissions(newPermissionsRequest);
回来
}
else if(isDataFetch)
{
mInterface.onLogin(会话);
}
其他的
{
mInterface.onLoginForShareData();
}
}
}
};
/**
*获取用户数据的方法
*@param session:引用活动session
*/
public void getDataFromFB(会话)
{
Request.executeRequestAsync(会话,新请求.GraphUserCallback()
{
//带有用户对象的Graph API响应后的回调
@凌驾
未完成公共无效(GraphUser用户,响应)
{
如果(用户!=null)
{
//用于检索用户数据并传递给注册片段的代码
FBBean fbUserDataBean=新FBBean();
if(mAccessTokenString!=null)
setAccessToken(MacAccessTokenString);
其他的
{
fbUserDataBean.setAccessToken(“”);
}
if(user.getUsername()!=null&!(user.getUsername().equals(null)))
fbUserDataBean.setUserName(user.getUsername());
其他的
{
fbUserDataBean.setUserName(“”);
}
if(user.getFirstName()!=null&!(user.getFirstName().equals(null)))
fbUserDataBean.setFirstNAme(user.getFirstName());
其他的
{
fbUserDataBean.setFirstNAme(“”);
}
if(user.getLastName()!=null&!(user.getLastName().equals(null)))
fbUserDataBean.setLastName(user.getLastName());
其他的
{
fbUserDataBean.setLastName(“”);
}
if(user.getbirth()!=null&!(user.getbirth().equals(null)))
fbUserDataBean.setUserBday(user.getBirthday());
其他的
{
fbUserDataBean.setUserBday(“”);
}
if(user.asMap().get(“性别”)!=null)
{
fbUserDataBean.setUserSex(user.asMap().get(“性别”).toString());
}
其他的
{
fbUserDataBean.setUserSex(“”);
}
如果(user.getProperty(“email”)!=null&&!(user.getProperty(“email”).equals(null)))
fbUserDataBean.setMailId(user.getProperty(“电子邮件”).toString());
其他的
{