cocos2d手游之微信分享SDK接入指南

前端之家收集整理的这篇文章主要介绍了cocos2d手游之微信分享SDK接入指南前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、微信分享SDK介绍

注:本文为微信Android终端开发工具的新手使用教程,只涉及教授SDK的使用方法,默认读者已经熟悉IDE的基本使用方法(本文以Eclipse为例),以及具有一定的编程知识基础等。


1.申请你的AppID
请到 开发者应用登记页面 进行登记,登记并选择移动应用进行设置后,将该应用提交审核,只有审核通过的应用才能进行开发。

2.下载微信终端开发工具包
开发工具包主要包含3部分内容:(其中,只有libammsdk.jar是必须的)
- libammsdk.jar(每个第三方应用必须要导入该sdk库,用于实现与微信的通信)
- API文档(供开发者查阅使用)
- 界面小工具源码(封装了界面表现的工具类,以及一些界面风格)
请前往“资源下载页”下载最新SDK包

3. 把下载下来的libmammsdk.jar直接拖入到安卓根目录的libs文件夹内

二、操作步骤

1. 配置AndroidManifest.xml,添加必要的权限支持,如下:
  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  3. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
  4. <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
  5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. 注册到微信

要使你的程序启动后微信终端能响应你的程序,必须在代码中向微信终端注册你的id。

  1. IWXAPI api = WXAPIFactory.createWXAPI(this,WXEntryActivity.APP_ID);
  2. api.registerApp(WXEntryActivity.APP_ID);
  3. api.handleIntent(getIntent(),this);

3. 发送图片

在这之前,由于微信4.2以下版本不支持发送到朋友圈,所以有个检测是否能否发送到朋友圈的方法

  1. private static boolean checkCanSendToFriend(IWXAPI api){
  2. int wxSdkVersion = api.getWXAppSupportAPI();
  3. if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
  4. return true;
  5. } else {
  6. return false;
  7. }
  8. }

另外一个微信自带生成唯一标识函数
  1. private static String buildTransaction(final String type) {
  2. return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  3. }

WXEntryActivity.java如下:
  1. package com.mz.maoxian.yunding.wxapi;
  2.  
  3.  
  4.  
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7.  
  8. import org.cocos2dx.lua.AppActivity;
  9.  
  10. import com.tencent.mm.sdk.openapi.BaseReq;
  11. import com.tencent.mm.sdk.openapi.BaseResp;
  12. import com.tencent.mm.sdk.openapi.ConstantsAPI;
  13. import com.tencent.mm.sdk.openapi.SendMessageToWX;
  14. import com.tencent.mm.sdk.openapi.IWXAPI;
  15. import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
  16. import com.tencent.mm.sdk.openapi.WXAPIFactory;
  17. import com.tencent.mm.sdk.openapi.WXImageObject;
  18. import com.tencent.mm.sdk.openapi.WXMediaMessage;
  19. import com.tencent.mm.sdk.openapi.WXTextObject;
  20. import com.tencent.mm.sdk.openapi.WXWebpageObject;
  21.  
  22.  
  23.  
  24. import android.app.Activity;
  25. import android.content.Intent;
  26. import android.content.res.AssetManager;
  27. import android.graphics.Bitmap;
  28. import android.graphics.BitmapFactory;
  29. import android.os.Bundle;
  30. import android.util.Log;
  31. import android.widget.Toast;
  32.  
  33.  
  34.  
  35. public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
  36. private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
  37. // IWXAPI 是第三方app和微信通信的openapi接口
  38. private static IWXAPI api = null;
  39. public static void myLog(String str)
  40. {
  41. Log.i("wc",str);
  42. }
  43. @Override
  44. public void onCreate(Bundle savedInstanceState) {
  45. super.onCreate(savedInstanceState);
  46. myLog("onCreate in Weixin entry");
  47. api.handleIntent(getIntent(),this);
  48. }
  49. private static String buildTransaction(final String type) {
  50. return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  51. }
  52. public static void sendImageWithAPI(IWXAPI aApi,AppActivity activity,int mode,String smallPng,String bigPng){
  53. Log.i("wc","smallPng:" + smallPng + " bigPng:" + bigPng);
  54. if(!checkInstallWeixin(aApi)){
  55. Toast.makeText(activity,"请确认您已安装微信客户端",Toast.LENGTH_LONG).show();
  56. return;
  57. }
  58. api = aApi;
  59. Bitmap bmpSmall = BitmapFactory.decodeFile(smallPng);
  60. Bitmap bmpBig = BitmapFactory.decodeFile(bigPng);
  61. if(bmpSmall == null){
  62. myLog("bmp is null");
  63. Toast.makeText(activity,"image path not find,path:" + smallPng,Toast.LENGTH_LONG).show();
  64. return;
  65. }
  66. if(bmpBig == null){
  67. myLog("bmp is null");
  68. Toast.makeText(activity,path:" + bigPng,Toast.LENGTH_LONG).show();
  69. return;
  70. }
  71. WXImageObject imgObj = new WXImageObject(bmpBig);
  72. WXMediaMessage msg = new WXMediaMessage();
  73. msg.mediaObject = imgObj;
  74. msg.thumbData = Util.bmpToByteArray(bmpSmall,true); // 设置缩略图
  75.  
  76. SendMessageToWX.Req req = new SendMessageToWX.Req();
  77. req.transaction = buildTransaction("img");
  78. req.message = msg;
  79. //聊天
  80. if(mode == 0){
  81. req.scene = SendMessageToWX.Req.WXSceneSession;
  82. api.sendReq(req);
  83. }
  84. //朋友圈
  85. else if((mode == 1) && (checkCanSendToFriend(api)))
  86. {
  87. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  88. api.sendReq(req);
  89. }
  90. else{
  91. Toast.makeText(activity,"您的微信客户端不支持分享到朋友圈!",Toast.LENGTH_LONG).show();
  92. }
  93. myLog("send img ok");
  94. }
  95. public static void sendURLWithAPI(IWXAPI aApi,String png,String title,String
  96. desc,String url,int mode)
  97. {
  98. if(!checkInstallWeixin(aApi)){
  99. Toast.makeText(activity,Toast.LENGTH_LONG).show();
  100. return;
  101. }
  102. api = aApi;
  103. Bitmap bmp = BitmapFactory.decodeFile(png);
  104. if(bmp == null){
  105. Toast.makeText(activity,path:" + png,Toast.LENGTH_LONG).show();
  106. return;
  107. }
  108. WXWebpageObject webpage = new WXWebpageObject();
  109. webpage.webpageUrl = url;
  110. WXMediaMessage msg = new WXMediaMessage(webpage);
  111. msg.title = title;
  112. msg.description = desc;
  113. Bitmap thumb = bmp;
  114. msg.thumbData = Util.bmpToByteArray(thumb,true);
  115. SendMessageToWX.Req req = new SendMessageToWX.Req();
  116. req.transaction = buildTransaction("webpage");
  117. req.message = msg;
  118.  
  119. //聊天
  120. if(mode == 0){
  121. req.scene = SendMessageToWX.Req.WXSceneSession;
  122. api.sendReq(req);
  123. }
  124. //朋友圈
  125. else if((mode == 1) && (checkCanSendToFriend(api)))
  126. {
  127. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  128. api.sendReq(req);
  129. }
  130. else{
  131. Toast.makeText(activity,Toast.LENGTH_LONG).show();
  132. }
  133. }
  134. @Override
  135. protected void onNewIntent(Intent intent) {
  136. super.onNewIntent(intent);
  137. Log.i("wc","onNewIntent");
  138. // setIntent(intent);
  139. // api.handleIntent(intent,this);
  140. }
  141.  
  142. // 微信发送请求到第三方应用时,会回调到该方法
  143. @Override
  144. public void onReq(BaseReq req) {
  145. Log.i("wc","onReq");
  146. switch (req.getType()) {
  147. case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
  148. //goToGetMsg();
  149. break;
  150. case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
  151. //goToShowMsg((ShowMessageFromWX.Req) req);
  152. break;
  153. default:
  154. break;
  155. }
  156. }
  157.  
  158. // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
  159. @Override
  160. public void onResp(BaseResp resp) {
  161. Log.i("wc","onResp");
  162. Log.i("wc",String.format("%d",resp.errCode));
  163.  
  164. switch (resp.errCode) {
  165. case BaseResp.ErrCode.ERR_OK:
  166. break;
  167. case BaseResp.ErrCode.ERR_USER_CANCEL:
  168.  
  169. break;
  170. case BaseResp.ErrCode.ERR_AUTH_DENIED:
  171.  
  172. break;
  173. default:
  174. break;
  175. }
  176. if(resp.errCode == BaseResp.ErrCode.ERR_OK)
  177. {
  178. backToAppActivityWithSuccess(true);
  179. }
  180. else
  181. {
  182. backToAppActivityWithSuccess(false);
  183. }
  184. }
  185. private void backToAppActivityWithSuccess(boolean success){
  186. if(success){
  187. AppActivity.nativeSendMessage("addevent;104");
  188. }else{
  189. AppActivity.nativeSendMessage("addevent;105");
  190. }
  191. finish();
  192. }
  193. private static boolean checkCanSendToFriend(IWXAPI api){
  194. int wxSdkVersion = api.getWXAppSupportAPI();
  195. myLog("sdkVersion:" + wxSdkVersion);
  196. if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
  197. return true;
  198. } else {
  199. return false;
  200. }
  201. }
  202. public static boolean checkInstallWeixin(IWXAPI api)
  203. {
  204. return api.getWXAppSupportAPI() != 0;
  205. }
  206. }

Util.java如下
  1. package com.mz.maoxian.yunding.wxapi;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.RandomAccessFile;
  8. import java.net.HttpURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12.  
  13. import junit.framework.Assert;
  14.  
  15. import android.graphics.Bitmap;
  16. import android.graphics.BitmapFactory;
  17. import android.graphics.Bitmap.CompressFormat;
  18. import android.util.Log;
  19.  
  20. public class Util {
  21. private static final String TAG = "SDK_Sample.Util";
  22. public static byte[] bmpToByteArray(final Bitmap bmp,final boolean needRecycle) {
  23. ByteArrayOutputStream output = new ByteArrayOutputStream();
  24. bmp.compress(CompressFormat.PNG,100,output);
  25. if (needRecycle) {
  26. bmp.recycle();
  27. }
  28. byte[] result = output.toByteArray();
  29. try {
  30. output.close();
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. return result;
  35. }
  36. public static byte[] getHtmlByteArray(final String url) {
  37. URL htmlUrl = null;
  38. InputStream inStream = null;
  39. try {
  40. htmlUrl = new URL(url);
  41. URLConnection connection = htmlUrl.openConnection();
  42. HttpURLConnection httpConnection = (HttpURLConnection)connection;
  43. int responseCode = httpConnection.getResponseCode();
  44. if(responseCode == HttpURLConnection.HTTP_OK){
  45. inStream = httpConnection.getInputStream();
  46. }
  47. } catch (MalformedURLException e) {
  48. e.printStackTrace();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. byte[] data = inputStreamToByte(inStream);
  53.  
  54. return data;
  55. }
  56. public static byte[] inputStreamToByte(InputStream is) {
  57. try{
  58. ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
  59. int ch;
  60. while ((ch = is.read()) != -1) {
  61. bytestream.write(ch);
  62. }
  63. byte imgdata[] = bytestream.toByteArray();
  64. bytestream.close();
  65. return imgdata;
  66. }catch(Exception e){
  67. e.printStackTrace();
  68. }
  69. return null;
  70. }
  71. public static byte[] readFromFile(String fileName,int offset,int len) {
  72. if (fileName == null) {
  73. return null;
  74. }
  75.  
  76. File file = new File(fileName);
  77. if (!file.exists()) {
  78. Log.i(TAG,"readFromFile: file not found");
  79. return null;
  80. }
  81.  
  82. if (len == -1) {
  83. len = (int) file.length();
  84. }
  85.  
  86. Log.d(TAG,"readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));
  87.  
  88. if(offset <0){
  89. Log.e(TAG,"readFromFile invalid offset:" + offset);
  90. return null;
  91. }
  92. if(len <=0 ){
  93. Log.e(TAG,"readFromFile invalid len:" + len);
  94. return null;
  95. }
  96. if(offset + len > (int) file.length()){
  97. Log.e(TAG,"readFromFile invalid file len:" + file.length());
  98. return null;
  99. }
  100.  
  101. byte[] b = null;
  102. try {
  103. RandomAccessFile in = new RandomAccessFile(fileName,"r");
  104. b = new byte[len]; // 创建合适文件大小的数组
  105. in.seek(offset);
  106. in.readFully(b);
  107. in.close();
  108.  
  109. } catch (Exception e) {
  110. Log.e(TAG,"readFromFile : errMsg = " + e.getMessage());
  111. e.printStackTrace();
  112. }
  113. return b;
  114. }
  115. private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;
  116. public static Bitmap extractThumbNail(final String path,final int height,final int width,final boolean crop) {
  117. Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);
  118.  
  119. BitmapFactory.Options options = new BitmapFactory.Options();
  120.  
  121. try {
  122. options.inJustDecodeBounds = true;
  123. Bitmap tmp = BitmapFactory.decodeFile(path,options);
  124. if (tmp != null) {
  125. tmp.recycle();
  126. tmp = null;
  127. }
  128.  
  129. Log.d(TAG,"extractThumbNail: round=" + width + "x" + height + ",crop=" + crop);
  130. final double beY = options.outHeight * 1.0 / height;
  131. final double beX = options.outWidth * 1.0 / width;
  132. Log.d(TAG,"extractThumbNail: extract beX = " + beX + ",beY = " + beY);
  133. options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
  134. if (options.inSampleSize <= 1) {
  135. options.inSampleSize = 1;
  136. }
  137.  
  138. // NOTE: out of memory error
  139. while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
  140. options.inSampleSize++;
  141. }
  142.  
  143. int newHeight = height;
  144. int newWidth = width;
  145. if (crop) {
  146. if (beY > beX) {
  147. newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
  148. } else {
  149. newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
  150. }
  151. } else {
  152. if (beY < beX) {
  153. newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
  154. } else {
  155. newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
  156. }
  157. }
  158.  
  159. options.inJustDecodeBounds = false;
  160.  
  161. Log.i(TAG,"bitmap required size=" + newWidth + "x" + newHeight + ",orig=" + options.outWidth + "x" + options.outHeight + ",sample=" + options.inSampleSize);
  162. Bitmap bm = BitmapFactory.decodeFile(path,options);
  163. if (bm == null) {
  164. Log.e(TAG,"bitmap decode Failed");
  165. return null;
  166. }
  167.  
  168. Log.i(TAG,"bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
  169. final Bitmap scale = Bitmap.createScaledBitmap(bm,newWidth,newHeight,true);
  170. if (scale != null) {
  171. bm.recycle();
  172. bm = scale;
  173. }
  174.  
  175. if (crop) {
  176. final Bitmap cropped = Bitmap.createBitmap(bm,(bm.getWidth() - width) >> 1,(bm.getHeight() - height) >> 1,width,height);
  177. if (cropped == null) {
  178. return bm;
  179. }
  180.  
  181. bm.recycle();
  182. bm = cropped;
  183. Log.i(TAG,"bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
  184. }
  185. return bm;
  186.  
  187. } catch (final OutOfMemoryError e) {
  188. Log.e(TAG,"decode bitmap Failed: " + e.getMessage());
  189. options = null;
  190. }
  191.  
  192. return null;
  193. }
  194. }

用法函数如下:
  1. private void sendWeixinImage(int mode,String bigPng,String weixinID){
  2. if(api == null)
  3. {
  4. api = WXAPIFactory.createWXAPI(this,weixinID);
  5. api.registerApp(weixinID);
  6. }
  7. WXEntryActivity.sendImageWithAPI(api,this,mode,smallPng,bigPng);
  8. }
  9. private void sendWeixinURL(String png,String desc,weixinID);
  10. api.registerApp(weixinID);
  11. }
  12. WXEntryActivity.sendURLWithAPI(api,png,title,desc,url,mode);
  13. }

注意点:

1. WXEntryActivity比如放在“ 包名.wxapi”目录下

2. 必须在微信后台配置包名对应的签名信息

3. 微信会保存签名缓存信息,必要的时候需要清除微信数据


至此,所有关键要素都已经说明,如果需要原码,请点击查看http://www.jb51.cc/article/p-kngrlkpy-bdv.html

猜你在找的Cocos2d-x相关文章