社交分享功能有助于游戏宣传和提升知名度,是一种不错的社交营销手段。
ShareSDK是一种社会化分享组件,为iOS、Android、WP8 的APP提供社会化功能,集成了一些常用的类库和接口,缩短开发者的开发时间,还有社会化统计分析管理后台。
参自百度百科:http://baike.baidu.com/view/9915538.htm?fr=aladdin
ShareSDK官网:http://sharesdk.cn
SDK下载:http://share.sharesdk.cn/Download
我们需要下载ShareSDK For iOS, ShareSDK For Android,ShareSDK For COCOS2D-X 这三个组件。
在ShareSDK官网注册一个账号,并添加新应用,得到此应用的AppKey,这个AppKey在下面我们将用的到。
在此只讲解 新浪微博,腾讯微博,微信朋友圈 三个平台的分享功能。
下面是集成步骤:
IOS端:
1.创建一个cocos2d-x工程,命名为ShareSDK。
2.将 ShareSDK For COCOS2D-X -> Classes 下的 C2DXShareSDK 拷贝到你项目的Classes目录下。
xcode中去除对Android目录的引用,只是去除引用,实际项目文件中要有此目录,项目编译到Android后才会用到。如图:
xcode中去除对Android目录的引用:
实际项目文件中保留:
3.将 ShareSDK For iOS 下的 ShareSDK 拷贝到你项目的iOS目录下。如图:
4.在 Link Binary With Libraries 中添加依赖库。如图:
添加以下framework到你的工程中:
SystemConfiguration.framework QuartzCore.framework CoreTelephony.framework libicucore.dylib libz.1.2.5.dylib Security.framework libstdc++.dylib 如果不需要QQ空间SSO登录和QQ好友分享可以不添加(这个如果是建立在你把SDK中对应的平台库文件删除掉,才能不添加,由于下载的SDK中每个平台的库都是默认存在的,所以必须要加上这个库,以下同理) libsqlite3.dylib 如果不需要QQ空间SSO登录和QQ好友分享可以不添加 CoreMotion.framework 如果不使用Google+可以不添加 CoreLocation.framework 如果不使用Google+可以不添加 MediaPlayer.framework 如果不使用Google+可以不添加 CoreText.framework 如果不使用Google+可以不添加 AssetsLibrary.framework 如果不使用Google+可以不添加 AddressBook.framework 如果不使用Google+可以不添加 MessageUI.framework 如果不集成邮件和短信可以不添加
5.打开“AppDelegate.cpp”文件,导入头文件“C2DXShareSDK.h”和命名空间 using namespace cn::sharesdk,完成初始化社交平台信息。代码如下:
// // ShareSDKAppDelegate.cpp // ShareSDK // // Created by XiangZi on 14-6-18. // Copyright __MyCompanyName__ 2014年. All rights reserved. // #include "AppDelegate.h" #include "cocos2d.h" #include "SimpleAudioEngine.h" #include "HelloWorldScene.h" #include "C2DXShareSDK.h" using namespace cn::sharesdk; USING_NS_CC; using namespace CocosDenshion; AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } bool AppDelegate::applicationDidFinishLaunching() { //*******************************************shareSDK*******************************************// C2DXShareSDK::open(CCString::create("211e0be667aa"), false);// 211e0be667aa 为你在ShareSDK官网添加应用的AppKey //初始化社交平台信息 this->initPlatformConfig(); //**********************************************************************************************// // initialize director CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); // turn on display FPS pDirector->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object CCScene *pScene = HelloWorld::scene(); // run pDirector->runWithScene(pScene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void AppDelegate::applicationDidEnterBackground() { CCDirector::sharedDirector()->stopAnimation(); SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic(); SimpleAudioEngine::sharedEngine()->pauseAllEffects(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { CCDirector::sharedDirector()->startAnimation(); SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic(); SimpleAudioEngine::sharedEngine()->resumeAllEffects(); } //*******************************************shareSDK*******************************************// /** 注意:可以根据自己需要集成的平台来选择部分平台进行初始化。配置中指定的AppKey等信息需要到相关的社会化平台中通过应用登记来获取。 1. app_key,app_secret,redirect_uri 这三个字段都需要你去各自官方平台注册得到。 2. 在info.plist中注册各平台app_key。 */ void AppDelegate::initPlatformConfig() { //新浪微博 别忘了在info.plist中注册 http://open.weibo.com CCDictionary *sinaConfigDict = CCDictionary::create(); sinaConfigDict -> setObject(CCString::create("568898243"), "app_key"); //app_key 应用标识 sinaConfigDict -> setObject(CCString::create("38a4f8204cc784f81f9f0daaf31e02e3"), "app_secret"); //app_secret 应用密钥 sinaConfigDict -> setObject(CCString::create("http://www.sharesdk.cn"), "redirect_uri"); //redirect_uri 回调地址 C2DXShareSDK::setPlatformConfig(C2DXPlatTypeSinaWeibo, sinaConfigDict); //腾讯微博 别忘了在info.plist中注册 http://dev.t.qq.com CCDictionary *tcConfigDict = CCDictionary::create(); tcConfigDict -> setObject(CCString::create("801307650"), "app_key"); tcConfigDict -> setObject(CCString::create("ae36f4ee3946e1cbb98d6965b0b2ff5c"), "app_secret"); tcConfigDict -> setObject(CCString::create("http://www.sharesdk.cn"), "redirect_uri"); C2DXShareSDK::setPlatformConfig(C2DXPlatTypeTencentWeibo, tcConfigDict); //微信朋友 别忘在info.plist中注册 http://open.weixin.qq.com/ 移动端上必须要装微信客户端,并且已连接互联网。 CCDictionary *wcConfigDict = CCDictionary::create(); wcConfigDict -> setObject(CCString::create("去官网申请"), "app_id"); wcConfigDict -> setObject(CCString::create("去官网申请"), "app_secret"); wcConfigDict -> setObject(CCString::create("http://www.sharesdk.cn"), "redirect_uri"); C2DXShareSDK::setPlatformConfig(C2DXPlatTypeWeixiTimeline, wcConfigDict); } //**********************************************************************************************//
6.在info.plist文件中添加一项用于客户端回调的URL Scheme。如图:
7.打开“AppController.mm”文件,修改如下:
// // ShareSDKAppController.mm // ShareSDK // // Created by XiangZi on 14-6-18. // Copyright __MyCompanyName__ 2014年. All rights reserved. // #import <UIKit/UIKit.h> #import "AppController.h" #import "cocos2d.h" #import "EAGLView.h" #import "AppDelegate.h" #import "RootViewController.h" //*******************************************shareSDK*******************************************// #import <ShareSDK/ShareSDK.h> #import "WXApi.h" //微信 #import "WeiboApi.h" //腾讯微博 //*********************************************************************************************// @implementation AppController @synthesize window; @synthesize viewController; #pragma mark - #pragma mark Application lifecycle // cocos2d application instance static AppDelegate s_sharedApplication; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //*******************************************shareSDK*******************************************// //导入微信类型 [ShareSDK importWeChatClass:[WXApi class]]; //导入腾讯微博类型 [ShareSDK importTencentWeiboClass:[WeiboApi class]]; //*********************************************************************************************// // Override point for customization after application launch. // Add the view controller's view to the window and display. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; EAGLView *__glView = [EAGLView viewWithFrame: [window bounds] pixelFormat: kEAGLColorFormatRGBA8 depthFormat: GL_DEPTH_COMPONENT16 preserveBackbuffer: NO sharegroup: nil multiSampling: NO numberOfSamples:0 ]; // Use RootViewController manage EAGLView viewController = [[RootViewController alloc] initWithNibName:nil bundle:nil]; viewController.wantsFullScreenLayout = YES; viewController.view = __glView; // Set RootViewController to window if ( [[UIDevice currentDevice].systemVersion floatValue] < 6.0) { // warning: addSubView doesn't work on iOS6 [window addSubview: viewController.view]; } else { // use this method on ios6 [window setRootViewController:viewController]; } [window makeKeyAndVisible]; [[UIApplication sharedApplication] setStatusBarHidden: YES]; cocos2d::CCApplication::sharedApplication()->run(); return YES; } - (void)applicationWillResignActive:(UIApplication *)application { /* Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ cocos2d::CCDirector::sharedDirector()->pause(); } - (void)applicationDidBecomeActive:(UIApplication *)application { /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ cocos2d::CCDirector::sharedDirector()->resume(); } - (void)applicationDidEnterBackground:(UIApplication *)application { /* Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ cocos2d::CCApplication::sharedApplication()->applicationDidEnterBackground(); } - (void)applicationWillEnterForeground:(UIApplication *)application { /* Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. */ cocos2d::CCApplication::sharedApplication()->applicationWillEnterForeground(); } - (void)applicationWillTerminate:(UIApplication *)application { /* Called when the application is about to terminate. See also applicationDidEnterBackground:. */ } #pragma mark - #pragma mark Memory management - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { /* Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */ cocos2d::CCDirector::sharedDirector()->purgeCachedData(); } - (void)dealloc { [super dealloc]; } //*******************************************shareSDK*******************************************// - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [ShareSDK handleOpenURL:url sourceApplication:nil annotation:nil wxDelegate:self]; } - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self]; } //*********************************************************************************************// @end
8.在HelloWorldScene.cpp中调用测试,代码如下:
<span style="color: rgb(62, 67, 73);">#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" //*******************************************shareSDK*******************************************// #include "C2DXShareSDK.h" using namespace cn::sharesdk; //*********************************************************************************************// using namespace cocos2d; using namespace CocosDenshion; CCScene* HelloWorld::scene() { CCScene *scene = CCScene::create(); HelloWorld *layer = HelloWorld::create(); scene->addChild(layer); return scene; } bool HelloWorld::init() { if ( !CCLayer::init() ) { return false; } CCSize size = CCDirector::sharedDirector()->getWinSize(); CCMenuItemLabel *shareMenuItem = CCMenuItemLabel::create(CCLabelTTF::create("分享社交平台", "Arial", 60),this,menu_selector(HelloWorld::shareMenuItemClick)); shareMenuItem->setPosition(ccp(size.width/2, size.height/2)); CCMenu* shareMenu = CCMenu::create(shareMenuItem,NULL); shareMenu->setPosition(CCPointZero); this->addChild(shareMenu); return true; } //*******************************************shareSDK*******************************************// void shareResultHandler(C2DXResponseState state, C2DXPlatType platType, CCDictionary *shareInfo, CCDictionary *error) { switch (state) { case C2DXResponseStateCancel: CCLog("取消"); break; case C2DXResponseStateSuccess: CCLog("分享成功"); break; case C2DXResponseStateFail: CCLog("分享失败"); break; default: break; } } void HelloWorld::shareMenuItemClick(CCObject* pSender) { //构造分享内容结构 对于新浪微博,腾讯微博而言是把content内容分享了上去,对于微信而言是分享了一个url链接。 CCDictionary *content = CCDictionary::create(); content -> setObject(CCString::create("ShareSDK-中国最大的App内分享服务提供商"), "title"); content -> setObject(CCString::create("ShareSDK是一种社会化分享组件,为iOS、Android、WP8 的APP提供社会化功能,集成了一些常用的类库和接口,缩短开发者的开发时间,还有社会化统计分析管理后台。http://sharesdk.cn"), "content"); content -> setObject(CCString::create("http://sharesdk.cn"), "url"); content -> setObject(CCString::create("http://img0.bdstatic.com/img/image/shouye/systsy-11927417755.jpg"), "image"); content -> setObject(CCString::createWithFormat("%d", C2DXContentTypeNews), "type"); C2DXShareSDK::showShareMenu(NULL, content, CCPointMake(100, 100), C2DXMenuArrowDirectionLeft, shareResultHandler); } //***********************************************************************************************//</span><span style="color:#ff0000;"> </span>
补充:
上面代码所分享的图片是来自网络的图片,可是如果我们要使用项目中本地的图片呢?一句代码搞定!Icon.png在项目Resources目录下,代码如下:
string imagePath = CCFileUtils::sharedFileUtils()->fullPathForFilename("Icon.png"); content -> setObject(CCString::create(imagePath.c_str()), "image");
9.删除不需要的平台库文件,从项目中彻底删除。库文件在 ShareSDK 下的 Connection 和 Extend 目录下:
删除前文件目录:
删除后文件目录:
10.用真机进行测试,结果成功!
到此IOS端结束。
Android端:
1.首先把 ShareSDK For COCOS2D-X -> proj.android ->assets 下 ShareSDK.xml拷贝到iOS项目Resources资源目录下,然后把ios项目编译到android,不会的同学请移步到:http://blog.csdn.net/song_hui_xiang/article/details/15815493
ShareSDK.xml 里面配置的信息是应用到各个分享平台的注册信息,此文件作用于Android平台。
编译好的Android目录结构:
用Eclipse打开proj.android项目。如图:
此时项目不能正常运行起来,因为用到的一些库还没有导入,继续下面操作。
2. 把 ShareSDK For COCOS2D-X ->proj.android -> libs目录下你所需要的架包复制到你的项目里。
因为我们只实现 新浪微博 腾讯微博 微信朋友圈 三个平台的分享动能,所以我们要复制这三个平台的jar包到相应目录下。此外还需要 libPluginProtocol.jar mframework.jar ShareSDK-Core-2.3.8.jar 这三个jar包。如图:
3. 把 ShareSDK For COCOS2D-X -> proj.android -> res-> drawable-xhdpi下的资源复制到你项目的 drawable-xhdpi下。
4.把 ShareSDK For COCOS2D-X -> proj.android -> res -> values 目录下的oks_string.xml、ssdk_string.xml复制到你的项目里的values目录下。如图:
5.把 ShareSDK For COCOS2D-X -> proj.android 里的AndroidManifest.xml里的<activity android:name="cn.sharesdk.framework.ShareSDKUIShell" />的属性和<user-permission>都复制到你的项目里的AndroidManifes.xml里,如果需要集成微信分享还需要设置微信的回调activity。
AndroidManifest.xml代码如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.cocos2dx.sharesdk" android:versionCode="1" android:versionName="1.0"> <!--shareSDK--> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <supports-screens android:largeScreens="true" android:smallScreens="true" android:anyDensity="true" android:resizeable="true" android:normalScreens="true"/> <!-- --> <uses-sdk android:minSdkVersion="8"/> <uses-feature android:glEsVersion="0x00020000" /> <application android:label="@string/app_name" android:icon="@drawable/icon"> <activity android:name=".ShareSDK" android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" android:configChanges="orientation"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!--shareSDK--> <activity android:name="cn.sharesdk.framework.ShareSDKUIShell" android:configChanges="keyboardHidden|orientation|screenSize" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:windowSoftInputMode="stateHidden|adjustResize" > </activity> <activity android:name=".wxapi.WXEntryActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:configChanges="keyboardHidden|orientation|screenSize" android:exported="true" android:screenOrientation="portrait" /> <!-- --> </application> <supports-screens android:largeScreens="true" android:smallScreens="true" android:anyDensity="true" android:normalScreens="true"/> </manifest>
6.把 ShareSDK For COCOS2D-X -> proj.android -> src下的整个文件夹cn拷贝到你项目下的src下,其中删除hellocpp文件夹。如图:
7.把 ShareSDK For COCOS2D-X -> proj.android -> src -> cn -> sharesdk -> hellocpp 下的wxapi文件夹拷贝到你项目 proj.android -> src -> org -> cocos2dx -> sharesdk 下。如图:
8.在主activity里的onCreate方法里添加ShareSDKUtils.prepare()方法。
package org.cocos2dx.sharesdk; import org.cocos2dx.lib.Cocos2dxActivity; import cn.sharesdk.ShareSDKUtils; import android.os.Bundle; public class ShareSDK extends Cocos2dxActivity{ protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); ShareSDKUtils.prepare(); } static { System.loadLibrary("game"); } }
9.修改项目assets下的ShareSDK.xml文件。只注册我们所需要的平台信息。
<?xml version="1.0" encoding="utf-8"?> <DevInfor> <!-- 说明: 1、表格中的第一项 <ShareSDK AppKey="api20" /> 是必须的,其中的AppKey是您在ShareSDK上注册的开发者帐号的AppKey 2、所有集成到您项目的平台都应该为其在表格中填写相对应的开发者信息,以新浪微博为例: <SinaWeibo Id="1" SortId="1" AppKey="568898243" AppSecret="38a4f8204cc784f81f9f0daaf31e02e3" RedirectUrl="http://www.sharesdk.cn" Enable="true" /> 其中的SortId是此平台在分享列表中的位置,由开发者自行定义,可以是任何整型数字,数值越大 越靠后AppKey、AppSecret和RedirectUrl是您在新浪微博上注册开发者信息和应用后得到的信息 Id是一个保留的识别符,整型,ShareSDK不使用此字段,供您在自己的项目中当作平台的识别符。 Enable字段表示此平台是否有效,布尔值,默认为true,如果Enable为false,即便平台的jar包 已经添加到应用中,平台实例依然不可获取。 各个平台注册应用信息的地址如下: 新浪微博 http://open.weibo.com 腾讯微博 http://dev.t.qq.com QQ空间 http://connect.qq.com/intro/login/ 微信好友 http://open.weixin.qq.com Facebook https://developers.facebook.com Twitter https://dev.twitter.com 人人网 http://dev.renren.com 开心网 http://open.kaixin001.com 搜狐微博 http://open.t.sohu.com 网易微博 http://open.t.163.com 豆瓣 http://developers.douban.com 有道云笔记 http://note.youdao.com/open/developguide.html#app 印象笔记 https://dev.evernote.com/ Linkedin https://www.linkedin.com/secure/developer?newapp= FourSquare https://developer.foursquare.com/ 搜狐随身看 https://open.sohu.com/ Flickr http://www.flickr.com/services/ Pinterest http://developers.pinterest.com/ Tumblr http://www.tumblr.com/developers Dropbox https://www.dropbox.com/developers Instagram http://instagram.com/developer# VKontakte http://vk.com/dev --> <ShareSDK AppKey = "200fe4a3ccb0"/> <!-- 修改成你在sharesdk后台注册的应用的appkey"--> <!-- ShareByAppClient标识是否使用微博客户端分享,默认是false --> <SinaWeibo Id="1" SortId="1" AppKey="568898243" AppSecret="38a4f8204cc784f81f9f0daaf31e02e3" RedirectUrl="http://www.sharesdk.cn" ShareByAppClient="true" Enable="true" /> <TencentWeibo Id="2" SortId="2" AppKey="801307650" AppSecret="ae36f4ee3946e1cbb98d6965b0b2ff5c" RedirectUri="http://www.sharesdk.cn" ShareByAppClient="true" Enable="true" /> <!-- Wechat微信和WechatMoments微信朋友圈的appid是一样的; 注意:开发者不能用我们这两个平台的appid,否则分享不了 微信测试的时候,微信测试需要先签名打包出apk, sample测试微信,要先签名打包,keystore在sample项目中,密码123456 BypassApproval是绕过审核的标记,设置为true后AppId将被忽略,故不经过 审核的应用也可以执行分享,但是仅限于分享文字和图片,不能分享其他类型, 默认值为false。此外,微信收藏不支持此字段。 --> <WechatMoments Id="5" SortId="5" AppId="wx51d9341a618ffc7c" BypassApproval="true" ShareByAppClient="true" Enable="true" /> </DevInfor>
10.用真机进行测试,结果成功!
备注一:微信、易信的注册和签名
对于微信和易信两个客户端(共五个平台)却还不行。因为这两个客户端的开放平台要求android第三方开发者需要提供自己项目的包名和签名,否则其客户端将拒绝第三方应用的分享操作。
apk签名请参考:http://wiki.sharesdk.cn/Android_快速集成指南
补充1:
QQ好友分享报错:尚未配置QQ好友分享的URL Scheme:QQ05FB8B52, 无法进行分享。
这是因为在info.plist文件中配置有问题。
解决:添加一项用于QQ客户端回调的URL Scheme,其格式为:"QQ” + AppId的16进制(如果appId转换的16进制数不够8位则在前面补0,如转换的是:5FB8B52,则最终填入为:QQ05FB8B52 注意:转换后的字母要大写)
如图: