- 使用eclipse導入proj.android掩驱。
- 創(chuàng)建包名.wxapi
-
導入微信sdk
- 創(chuàng)建JinHelper.java
- AppActivity.java
public static final String TAG = "NiuBuTing_Weixin_SDK";
public static final String APP_ID = "你的APP_iD";
public static IWXAPI api;
private static AppActivity instance = null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
// 注冊到微信
regToWx();
}
//注冊到微信
private void regToWx() {
//工廠模式創(chuàng)建微信api
api = WXAPIFactory.createWXAPI(this, APP_ID, false);
//注冊程序
api.registerApp(APP_ID);
}
//啟動微信
private static boolean LaunchWX() {
boolean ret = false;
if (!api.isWXAppInstalled())
{//判斷是否安裝微信
Toast.makeText(instance, "沒有安裝微信芒划,請先安裝微信!", Toast.LENGTH_LONG).show();
return ret;
}
if (api.openWXApp())
{//判斷打開微信是否成功
Log.d(TAG, "微信打開成功!");
ret = true;
}
else
{
Log.d(TAG, "微信打開失敗!");
ret = false;
}
return ret;
}
//將圖片解析成一個二進制數(shù)組
private byte[] bmpToByteArrar(final Bitmap bitmap, final boolean isRecycle){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
if (isRecycle)
{
bitmap.recycle();
}
byte[] result = outputStream.toByteArray();
try
{
outputStream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
//微信登錄
public static void WXLogin(){
Log.d(TAG, "login-------------");
WXEntryActivity.ReqState = 0;
final SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo"; //這里不能改
req.state = "QTNiuBuTing"; //這里改成你自己的數(shù)據(jù)
api.sendReq(req);
}
//分享到聊天窗口
public static void WXShareMsgToFriends(final String userNickName,
final String roomNum,
final String inningsNum,
final String peopleNum,
final int playType){
//這里的參數(shù)是看你自己你需要的話就行,但是在cocos里面調用這個方法的你也傳遞數(shù)值過來
String strPlayType = "輪莊牛牛";
if (playType == 1) //2為輪莊
{
strPlayType = "搶莊牛牛";
}
WXEntryActivity.ReqState = 1;
//封裝一個鏈接欧穴,點擊跳轉到指定網址
WXWebpageObject webpag = new WXWebpageObject();
webpag.webpageUrl = "https://www.xxxxxxxxxxxxx.com/";
//封裝游戲圖標
Bitmap bitmap = BitmapFactory.decodeResource(instance.getResources(), R.drawable.icon);
Bitmap thumb = Bitmap.createScaledBitmap(bitmap, 108, 108, true);
bitmap.recycle();
//封裝分享內容
WXMediaMessage msg = new WXMediaMessage(webpag);
msg.thumbData = instance.bmpToByteArrar(thumb, true);
msg.title = "我是 " + userNickName; //這個是標題
msg.description = "[" + strPlayType + "]" //這個是描述
+ " 房間號:" + roomNum + "民逼。"
+ " 局數(shù):" + inningsNum + "。"
+ " 人數(shù):" + peopleNum + "人涮帘。"
+ "一起來玩一玩吧拼苍!";
//封裝請求
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpag");
req.message = msg;
req.scene = SendMessageToWX.Req.WXSceneSession;
//發(fā)送請求
api.sendReq(req);
}
//生成一個微信唯一請求標識符
private static String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
- WXEntryActivity.java
放到包名.wxapi文件夾下
WXEntryActivity.java 和 .wxapi 不要改名
包名對應的是微信記錄的那個包名
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private final String TAG = "NiuBuTing_Weixin_SDK";
public static int ReqState = -1; //0為登錄, 1為分享
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AppActivity.api.handleIntent(this.getIntent(), this);
//如果沒回調onResp调缨,八成是這句沒有寫
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
AppActivity.api.handleIntent(intent, this);
}
// 微信發(fā)送請求到第三方應用時疮鲫,會回調到該方法
@Override
public void onReq(BaseReq req) {
finish();
}
@Override
public void onResp(BaseResp resp) {
Log.d(TAG, "onResp:");
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
Log.d(TAG, "請求成功");
if (ReqState == 0) //這個是自己加用于判斷是登錄還是分享,你們可以去掉判斷只要里面的代碼就行了
{
SendAuth.Resp sendResp = (SendAuth.Resp) resp;
JniHelper.onResp(sendResp.code); //這個登錄了之后用于回調cocos端函數(shù)的映射代碼
Log.d(TAG, sendResp.code);
}
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
//發(fā)送取消
Toast.makeText(this, "請求取消", Toast.LENGTH_LONG).show();
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
//發(fā)送被拒絕
Toast.makeText(this, "請求被拒絕", Toast.LENGTH_LONG).show();
break;
default:
//發(fā)送返回
Toast.makeText(this, "請求返回", Toast.LENGTH_LONG).show();
break;
}
ReqState = -1;
finish();
}
}
-
AndroidManifest.xml
- WXAPIManager.h
#ifndef __WXAPIMANAGER_H__
#define __WXAPIMANAGER_H__
#include "cocos2d.h"
#include "network/HttpClient.h"
USING_NS_CC;
using namespace network;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //判斷是不是安卓環(huán)境
#include "platform/android/jni/JniHelper.h"
#endif
typedef enum {
REQ_ERROR = 0,
REQ_SUCCESS,
CMD_ACCESS_TOKEN,
CMD_USER_INFO,
DEFAULT
}reqTag;
class WXAPIManager : Ref
{
public:
static WXAPIManager *getInstance();
//分享到好友
void sendToFriend(const char *userNickName, const char *roomNum, const char *inningsNum, const char *peopleNum, const int playType);
//微信登錄
void loginWX();
public:
static WXAPIManager *_instance;
void setCode(std::string szCode);
private:
WXAPIManager();
~WXAPIManager();
std::string code;
reqTag lastTag;
};
#endif // __WXAPIMANAGER_H__</void(std::string)>
- WXAPIManager.cpp
#include "WXAPIManager.h"
WXAPIManager *WXAPIManager::_instance = nullptr;
WXAPIManager::WXAPIManager()
:lastTag(reqTag::CMD_ACCESS_TOKEN)
{
}
WXAPIManager::~WXAPIManager()
{
}
WXAPIManager *WXAPIManager::getInstance()
{
if (_instance == nullptr)
{
_instance = new(std::nothrow) WXAPIManager();
_instance->autorelease();
_instance->retain();
}
return _instance;
}
//分享給好友
void WXAPIManager::sendToFriend(const char *userNickName, const char *roomNum, const char *inningsNum, const char *peopleNum, const int playType)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) //判斷是不是Android環(huán)境
JniMethodInfo minfo;
//調用java端的靜態(tài)函數(shù)
bool isHave = JniHelper::getStaticMethodInfo(minfo,
"org/cocos2dx/cpp/AppActivity", //這個是固定的
"WXShareMsgToFriends", //這個是你要調用的java端的函數(shù)名
"(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V");
//后面跟的是java那邊需要接收的參數(shù)
if (!isHave) {
log("jni:WXShareImgToFriends is null");
}
else {
//這里需要把參數(shù)轉換為java格式
jstring jUserNickName = minfo.env->NewStringUTF(userNickName);
jstring jRoomNum = minfo.env->NewStringUTF(roomNum);
jstring jInnings = minfo.env->NewStringUTF(inningsNum);
jstring jpeopleNum = minfo.env->NewStringUTF(peopleNum);
jint jPlayType = playType;
minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID, jUserNickName, jRoomNum, jInnings, jpeopleNum, jPlayType); //開始調用函數(shù)
//刪除參數(shù)
minfo.env->DeleteLocalRef(jUserNickName);
minfo.env->DeleteLocalRef(jRoomNum);
minfo.env->DeleteLocalRef(jInnings);
minfo.env->DeleteLocalRef(jpeopleNum);
}
#endif
}
//微信登錄
void WXAPIManager::loginWX()
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
JniMethodInfo minfo;
bool isHave = JniHelper::getStaticMethodInfo(minfo,
"org/cocos2dx/cpp/AppActivity",
"WXLogin",
"()V"); //沒有參數(shù)
if (!isHave) {
log("jni:WXLogin is null");
}
else
{
minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID);
}
#endif
}
void WXAPIManager :: setCode(std::string szCode) {
code = szCode;
//發(fā)送code值
auto _eventDispatcher = Director::getInstance()->getEventDispatcher();
_eventDispatcher->dispatchCustomEvent("code", &szCode);
}
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
//必須是C語言的函數(shù)弦叶,因為C++的函數(shù)會有不同的符號生成規(guī)則
//1.Java_:是格式俊犯,必須加的
//2.org_cocos2dx_cpp_tools_JniHelper:是包名+類名
//3.onResp:是Andriod工程中聲明的名字
//4.中間需要_分開
extern "C" {
//給android調用的native代碼,微信回調后會調用這個函數(shù)
//這個代碼是給安卓調用伤哺,那邊傳了一個code過來直接轉換之后使用就行了
/*
微信的登錄的流程:
1燕侠、拉起微信登錄界面,用戶確認之后就回調java端的回調立莉。
2绢彤、Java端的回調執(zhí)行之后根據(jù)代碼在調用這個函數(shù)。
3蜓耻、接下來的步驟有cocos基礎的基本都知道怎么執(zhí)行了
所以在cocos端首先執(zhí)行的就是這里的代碼茫舶。
*/
JNIEXPORT void Java_org_cocos2dx_cpp_JniHelper_onResp(JNIEnv *env, jobject thiz, jstring code)
{
/*獲取code值,進行類型轉換*/
const char *szCode = env->GetStringUTFChars(code, NULL);
std::string sCode = szCode;
/*調用setCode()方法*/
WXAPIManager *_twm = WXAPIManager::getInstance();
_twm->setCode(sCode);
}
}
#endif</char>
微信登錄
//微信登錄 放到點擊事件里
auto manager = WXAPIManager::getInstance();
manager->loginWX();
/*接收code值*/
_eventDispatcher->addCustomEventListener("code", [=](EventCustom* evn) {
std::string* strValue = (std::string*)(evn->getUserData());
Size size = Director::getInstance()->getWinSize();
code = *strValue;
/*顯示所獲得的code值*/
TTFConfig nameTtf("font/ffa.ttf", 16);//字體自己隨便找個
nameTypeface = Label::createWithTTF(nameTtf, "423");
nameTypeface->setTextColor(Color4B::BLUE);
nameTypeface->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
nameTypeface->setPosition(size/2);
nameTypeface->setString(code);
addChild(nameTypeface);
/*然后給服務器發(fā)送code值*/
Label* nameTypeface;放到方法外面,不要放到.h文件里會打包出錯刹淌。放方法里面的話Label會不顯示
-
打包