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;

	@Override
	protected 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()
	{
		@Override
		public 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()
		{
			@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(MainActivity.this, "Posted story, id: " + postId, Toast.LENGTH_SHORT).show();
					} else
					{
						// User clicked the Cancel button
						Toast.makeText(MainActivity.this, "Publish cancelled", Toast.LENGTH_SHORT).show();
					}
				} else if (error instanceof FacebookOperationCanceledException)
				{
					// User clicked the "x" button
					Toast.makeText(MainActivity.this, "Publish cancelled", Toast.LENGTH_SHORT).show();
				} else
				{
					// Generic, ex: network error
					Toast.makeText(MainActivity.this, "Error posting story", Toast.LENGTH_SHORT).show();
				}
			}
		}).build();
		feedDialog.show();
	}

	@Override
	public void onClick(View v)
	{
		if (Session.getActiveSession() == null || !Session.getActiveSession().isOpened())
		{
			Session.openActiveSession(MainActivity.this, true, callback);
		} else
		{
			publishFeedDialog();
		}
	}

	//  Life

	@Override
	protected void onPause()
	{
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		uiHelper.onResume();
	}

	@Override
	protected 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()
	{
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data)
		{
			Log.e("MainActivity", String.format("Error: %s", error.toString()));
		}

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

}

  设置 Facebook相关的Activity

        <!-- facebook相关 -->
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

添加联网的权限即可.


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方法

   

// 分享到 FaceBook
void 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
}
即可.



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值