Android下进行 Facebook 分享

1.  下载 Facebook SDK

2.  在facebook下设置app的相关信息

3.  示例代码:

     

package com.example.testshare;import com.example.zcsocial.R;import com.facebook.FacebookException;import com.facebook.FacebookOperationCanceledException;import com.facebook.Session;import com.facebook.SessionState;import com.facebook.UiLifecycleHelper;import com.facebook.widget.FacebookDialog;import com.facebook.widget.WebDialog;import com.facebook.widget.WebDialog.FeedDialogBuilder;import com.facebook.widget.WebDialog.OnCompleteListener;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Toast;public class MainActivity extends Activity implements OnClickListener{public static final String TAG = "MainActivity";// /////////////////////////////////////////////////private UiLifecycleHelper uiHelper;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);uiHelper = new UiLifecycleHelper(this, null);uiHelper.onCreate(savedInstanceState);// //////////////////findViewById(R.id.btn).setOnClickListener(this);}private Session.StatusCallback callback = new Session.StatusCallback(){@Overridepublic void call(Session session, SessionState state, Exception exception){if (state.isOpened()){publishFeedDialog();} else{Log.e(TAG, "Error:" + exception.getMessage());}}};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");FeedDialogBuilder dialogBuilder = new WebDialog.FeedDialogBuilder(this, Session.getActiveSession(), params);WebDialog feedDialog = dialogBuilder.setOnCompleteListener(new OnCompleteListener(){@Overridepublic 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(MainActivity.this, "Posted story, id: " + postId, Toast.LENGTH_SHORT).show();} else{// User clicked the Cancel buttonToast.makeText(MainActivity.this, "Publish cancelled", Toast.LENGTH_SHORT).show();}} else if (error instanceof FacebookOperationCanceledException){// User clicked the "x" buttonToast.makeText(MainActivity.this, "Publish cancelled", Toast.LENGTH_SHORT).show();} else{// Generic, ex: network errorToast.makeText(MainActivity.this, "Error posting story", Toast.LENGTH_SHORT).show();}}}).build();feedDialog.show();}@Overridepublic void onClick(View v){if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened()){Session.openActiveSession(MainActivity.this, true, callback);} else{publishFeedDialog();}}// //////////////// Life@Overrideprotected void onPause(){super.onPause();uiHelper.onPause();}@Overrideprotected void onDestroy(){super.onDestroy();uiHelper.onDestroy();}@Overrideprotected void onResume(){super.onResume();uiHelper.onResume();}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data){super.onActivityResult(requestCode, resultCode, data);uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);}private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback(){@Overridepublic void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data){Log.e("MainActivity", String.format("Error: %s", error.toString()));}@Overridepublic void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data){Log.e("MainActivity", "Success!");}};}

  设置 Facebook相关的Activity

                        

添加联网的权限即可.


4.总结下,就是  先检查Facebook的Seesion是否已经打开,如果没有打开,则先打开,否则直接进行分享.


---------------------------------------------------------分割线----------------------------------------------------------

cocos2dx IOS下添加 Facebook 分享

1.下载并添加Facebook SDK,在Info.plist 里面设置好相应的数据

    FacebookAppID                        xxxxxxxxx

    FacebookDisplayName              My IOS APP

    URL types

    ---------Item 0

    ----------------URL Schemes

    ---------------------------Item 0                fbxxxxxxxx



2. 在 RootViewController.h .mm里面添加一个函数

    

- (NSDictionary*)parseURLParams:(NSString *)query {    NSArray *pairs = [query componentsSeparatedByString:@"&"];    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];    for (NSString *pair in pairs) {        NSArray *kv = [pair componentsSeparatedByString:@"="];        NSString *val =        [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];        params[kv[0]] = val;    }    return params;  }

3.添加 share方法

   

// 分享到 FaceBookvoid IOSPlatform::shareFacebook(){    #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS        // Put together the dialog parameters    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:                                   @"Sharing Tutorial", @"name",                                   @"Build great social apps and get more installs.", @"caption",                                   @"Allow your users to share stories on Facebook from your app using the iOS SDK.", @"description",                                   @"https://developers.facebook.com/docs/ios/share/", @"link",                                   @"http://i.imgur.com/g3Qc1HN.png", @"picture",                                   nil];        // Show the feed dialog    [FBWebDialogs presentFeedDialogModallyWithSession:nil                                           parameters:params                                              handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {                                                  if (error) {                                                      // An error occurred, we need to handle the error                                                      // See: https://developers.facebook.com/docs/ios/errors                                                      NSLog([NSString stringWithFormat:@"Error publishing story: %@", error.description]);                                                  } else {                                                      if (result == FBWebDialogResultDialogNotCompleted) {                                                          // User cancelled.                                                          NSLog(@"User cancelled.");                                                      } else {                                                          // Handle the publish feed callback                                                          NSDictionary *urlParams = [_gRootViewController parseURLParams:[resultURL query]];                                                                                                                    if (![urlParams valueForKey:@"post_id"]) {                                                              // User cancelled.                                                              NSLog(@"User cancelled.");                                                                                                                        } else {                                                              // User clicked the Share button                                                              NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];                                                              NSLog(@"result %@", result);                                                          }                                                      }                                                  }                                              }];    #endif}
即可.