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,添加必要的权限支持,如下:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> 
<uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

2. 注册到微信

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

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

3. 发送图片

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

private static boolean checkCanSendToFriend(IWXAPI api){
		int wxSdkVersion = api.getWXAppSupportAPI();
		if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
			return true;
		} else {
			return false;
		}
	}

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

WXEntryActivity.java如下:
package com.mz.maoxian.yunding.wxapi;



import java.io.IOException;
import java.io.InputStream;

import org.cocos2dx.lua.AppActivity;

import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.mm.sdk.openapi.WXWebpageObject;



import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;



public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
	
	private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
	// IWXAPI 是第三方app和微信通信的openapi接口
    private static IWXAPI api = null;
    
    public static void myLog(String str)
    {
    	Log.i("wc",str);
    }
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myLog("onCreate in Weixin entry");
        api.handleIntent(getIntent(),this);
    }
    private static String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
   
    public static void sendImageWithAPI(IWXAPI aApi,AppActivity activity,int mode,String smallPng,String bigPng){
    	Log.i("wc","smallPng:" + smallPng + " bigPng:" + bigPng);
    	if(!checkInstallWeixin(aApi)){
    		Toast.makeText(activity,"请确认您已安装微信客户端",Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	api = aApi;
    	Bitmap bmpSmall = BitmapFactory.decodeFile(smallPng);
    	Bitmap bmpBig = BitmapFactory.decodeFile(bigPng);
    	if(bmpSmall == null){
    		myLog("bmp is null");
    		Toast.makeText(activity,"image path not find,path:" + smallPng,Toast.LENGTH_LONG).show();
    		return;
    	}
    	if(bmpBig == null){
    		myLog("bmp is null");
    		Toast.makeText(activity,path:" + bigPng,Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	WXImageObject imgObj = new WXImageObject(bmpBig);
		
		WXMediaMessage msg = new WXMediaMessage();
		msg.mediaObject = imgObj;
		
		msg.thumbData = Util.bmpToByteArray(bmpSmall,true);  // 设置缩略图

		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("img");
		req.message = msg;
		
		//聊天
		if(mode == 0){
			req.scene = SendMessageToWX.Req.WXSceneSession;
			api.sendReq(req);
		}
		//朋友圈
		else if((mode == 1) && (checkCanSendToFriend(api)))
		{
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
			api.sendReq(req);
		}
		else{
			Toast.makeText(activity,"您的微信客户端不支持分享到朋友圈!",Toast.LENGTH_LONG).show();
		}
		myLog("send img ok");
    }
    public static void sendURLWithAPI(IWXAPI aApi,String png,String title,String 
    		desc,String url,int mode)
    {	
    	if(!checkInstallWeixin(aApi)){
    		Toast.makeText(activity,Toast.LENGTH_LONG).show();
    		return;
    	}
    	api = aApi;
    	
    	Bitmap bmp = BitmapFactory.decodeFile(png);
    	
    	if(bmp == null){
    		Toast.makeText(activity,path:" + png,Toast.LENGTH_LONG).show();
    		return;
    	}
    	
    	WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url;
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = title;
		msg.description =  desc;
		Bitmap thumb = bmp;
		msg.thumbData = Util.bmpToByteArray(thumb,true);
		
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;

		//聊天
		if(mode == 0){
			req.scene = SendMessageToWX.Req.WXSceneSession;
			api.sendReq(req);
		}
		//朋友圈
		else if((mode == 1) && (checkCanSendToFriend(api)))
		{
			req.scene = SendMessageToWX.Req.WXSceneTimeline;
			api.sendReq(req);
		}
		else{
			Toast.makeText(activity,Toast.LENGTH_LONG).show();
		}
    }
    
    
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Log.i("wc","onNewIntent");
//		setIntent(intent);
//        api.handleIntent(intent,this);
	}

	// 微信发送请求到第三方应用时,会回调到该方法
	@Override
	public void onReq(BaseReq req) {
		
		Log.i("wc","onReq");
		
		switch (req.getType()) {
		case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
			//goToGetMsg();		
			break;
		case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
			//goToShowMsg((ShowMessageFromWX.Req) req);
			break;
		default:
			break;
		}
	}

	// 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
	@Override
	public void onResp(BaseResp resp) {
		
		Log.i("wc","onResp");
 		Log.i("wc",String.format("%d",resp.errCode));

		switch (resp.errCode) {
		case BaseResp.ErrCode.ERR_OK:
			
			break;
		case BaseResp.ErrCode.ERR_USER_CANCEL:

			break;
		case BaseResp.ErrCode.ERR_AUTH_DENIED:

			break;
		default:
			
			break;
		}
		
		if(resp.errCode == BaseResp.ErrCode.ERR_OK)
		{
			backToAppActivityWithSuccess(true);
		}
		else
		{
			backToAppActivityWithSuccess(false);
		}
		
		
	}
	private void backToAppActivityWithSuccess(boolean success){
		if(success){
			AppActivity.nativeSendMessage("addevent;104");
		}else{
			AppActivity.nativeSendMessage("addevent;105");
		}
		
		finish();
	}
	
	
	private static boolean checkCanSendToFriend(IWXAPI api){
		int wxSdkVersion = api.getWXAppSupportAPI();
		
		myLog("sdkVersion:" + wxSdkVersion);
		if (wxSdkVersion >= TIMELINE_SUPPORTED_VERSION) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean checkInstallWeixin(IWXAPI api)
	{
		return api.getWXAppSupportAPI() != 0;
	}
}

Util.java如下
package com.mz.maoxian.yunding.wxapi;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import junit.framework.Assert;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;

public class Util {
	
	private static final String TAG = "SDK_Sample.Util";
	
	public static byte[] bmpToByteArray(final Bitmap bmp,final boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG,100,output);
		if (needRecycle) {
			bmp.recycle();
		}
		
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static byte[] getHtmlByteArray(final String url) {
		 URL htmlUrl = null;     
		 InputStream inStream = null;     
		 try {         
			 htmlUrl = new URL(url);         
			 URLConnection connection = htmlUrl.openConnection();         
			 HttpURLConnection httpConnection = (HttpURLConnection)connection;         
			 int responseCode = httpConnection.getResponseCode();         
			 if(responseCode == HttpURLConnection.HTTP_OK){             
				 inStream = httpConnection.getInputStream();         
			  }     
			 } catch (MalformedURLException e) {               
				 e.printStackTrace();     
			 } catch (IOException e) {              
				e.printStackTrace();    
		  } 
		byte[] data = inputStreamToByte(inStream);

		return data;
	}
	
	public static byte[] inputStreamToByte(InputStream is) {
		try{
			ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
			int ch;
			while ((ch = is.read()) != -1) {
				bytestream.write(ch);
			}
			byte imgdata[] = bytestream.toByteArray();
			bytestream.close();
			return imgdata;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static byte[] readFromFile(String fileName,int offset,int len) {
		if (fileName == null) {
			return null;
		}

		File file = new File(fileName);
		if (!file.exists()) {
			Log.i(TAG,"readFromFile: file not found");
			return null;
		}

		if (len == -1) {
			len = (int) file.length();
		}

		Log.d(TAG,"readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));

		if(offset <0){
			Log.e(TAG,"readFromFile invalid offset:" + offset);
			return null;
		}
		if(len <=0 ){
			Log.e(TAG,"readFromFile invalid len:" + len);
			return null;
		}
		if(offset + len > (int) file.length()){
			Log.e(TAG,"readFromFile invalid file len:" + file.length());
			return null;
		}

		byte[] b = null;
		try {
			RandomAccessFile in = new RandomAccessFile(fileName,"r");
			b = new byte[len]; // 创建合适文件大小的数组
			in.seek(offset);
			in.readFully(b);
			in.close();

		} catch (Exception e) {
			Log.e(TAG,"readFromFile : errMsg = " + e.getMessage());
			e.printStackTrace();
		}
		return b;
	}
	
	private static final int MAX_DECODE_PICTURE_SIZE = 1920 * 1440;
	public static Bitmap extractThumbNail(final String path,final int height,final int width,final boolean crop) {
		Assert.assertTrue(path != null && !path.equals("") && height > 0 && width > 0);

		BitmapFactory.Options options = new BitmapFactory.Options();

		try {
			options.inJustDecodeBounds = true;
			Bitmap tmp = BitmapFactory.decodeFile(path,options);
			if (tmp != null) {
				tmp.recycle();
				tmp = null;
			}

			Log.d(TAG,"extractThumbNail: round=" + width + "x" + height + ",crop=" + crop);
			final double beY = options.outHeight * 1.0 / height;
			final double beX = options.outWidth * 1.0 / width;
			Log.d(TAG,"extractThumbNail: extract beX = " + beX + ",beY = " + beY);
			options.inSampleSize = (int) (crop ? (beY > beX ? beX : beY) : (beY < beX ? beX : beY));
			if (options.inSampleSize <= 1) {
				options.inSampleSize = 1;
			}

			// NOTE: out of memory error
			while (options.outHeight * options.outWidth / options.inSampleSize > MAX_DECODE_PICTURE_SIZE) {
				options.inSampleSize++;
			}

			int newHeight = height;
			int newWidth = width;
			if (crop) {
				if (beY > beX) {
					newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
				} else {
					newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
				}
			} else {
				if (beY < beX) {
					newHeight = (int) (newWidth * 1.0 * options.outHeight / options.outWidth);
				} else {
					newWidth = (int) (newHeight * 1.0 * options.outWidth / options.outHeight);
				}
			}

			options.inJustDecodeBounds = false;

			Log.i(TAG,"bitmap required size=" + newWidth + "x" + newHeight + ",orig=" + options.outWidth + "x" + options.outHeight + ",sample=" + options.inSampleSize);
			Bitmap bm = BitmapFactory.decodeFile(path,options);
			if (bm == null) {
				Log.e(TAG,"bitmap decode Failed");
				return null;
			}

			Log.i(TAG,"bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
			final Bitmap scale = Bitmap.createScaledBitmap(bm,newWidth,newHeight,true);
			if (scale != null) {
				bm.recycle();
				bm = scale;
			}

			if (crop) {
				final Bitmap cropped = Bitmap.createBitmap(bm,(bm.getWidth() - width) >> 1,(bm.getHeight() - height) >> 1,width,height);
				if (cropped == null) {
					return bm;
				}

				bm.recycle();
				bm = cropped;
				Log.i(TAG,"bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
			}
			return bm;

		} catch (final OutOfMemoryError e) {
			Log.e(TAG,"decode bitmap Failed: " + e.getMessage());
			options = null;
		}

		return null;
	}
}

用法函数如下:
private void sendWeixinImage(int mode,String bigPng,String weixinID){
		if(api == null)
		{
			api = WXAPIFactory.createWXAPI(this,weixinID);
			api.registerApp(weixinID);
		}
		WXEntryActivity.sendImageWithAPI(api,this,mode,smallPng,bigPng);
	}
	private void sendWeixinURL(String png,String desc,weixinID);
			api.registerApp(weixinID);
		}
		WXEntryActivity.sendURLWithAPI(api,png,title,desc,url,mode);
	}

注意点:

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

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

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


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

原文链接:https://www.f2er.com/cocos2dx/340332.html

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