[迁移]cocos2d-x 中关于JniHelper的使用

声明:因网易博客将关闭,移到此

这里主要在cocos2d-x中调用android中类的静态函数,如果是普通函数就自己探索了

说多无益,直接上代码

cocos2d-x部分

#ifndef __HELPER_H__
#define __HELPER_H__

#include <iostream>

namespace MGame
{
class PlatformHelper
{
public:
static PlatformHelper *shared();
void doAction(const std::string& key, const std::string& message);
};
}


#endif // __HELPER_H__

#include "PlatformHelper.h"
#include "cocos2d.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) 
#include <jni.h> 
#include "platform/android/jni/JniHelper.h" 
#include <android/log.h> 
#endif

//===================== android ======================
#define ANDROID_CLASS_NAME "org/cocos2dx/Game/JavaHelper"
#define ANDROID_FUNCTION_NAME "doAction"
#define ANDROID_PARAM_TYPE "(Ljava/lang/String;Ljava/lang/String;)V"


namespace MGame
{
static PlatformHelper * s_PlatformHelperShared = NULL;

PlatformHelper *PlatformHelper::shared()
{
if (s_PlatformHelperShared == NULL)
s_PlatformHelperShared = new PlatformHelper;
return s_PlatformHelperShared;
}

void PlatformHelper::doAction(const std::string& key, const std::string& message)
{
// android
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
USING_NS_CC;
JniMethodInfo methodInfo;
bool isHave = JniHelper::getStaticMethodInfo(methodInfo, ANDROID_CLASS_NAME,
ANDROID_FUNCTION_NAME,
ANDROID_PARAM_TYPE);
if (isHave)
{
jstring key_arg = methodInfo.env->NewStringUTF(key.c_str());
jstring msg_arg = methodInfo.env->NewStringUTF(message.c_str());

methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, key_arg, msg_arg);
}
else
{

}
#else

#endif 
}
}

java部分
package org.cocos2dx.Game;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

public class JavaHelper {

private static Context s_context;
/**
 * 初始化内容信息
 * @param context
 */
public static void initContext(Context context){
s_context = context;
}
public static void doAction(String key, String message){
Message msg = new Message();
msg.what = Integer.parseInt(key);
msg.obj = message;
handler.sendMessage(msg);
}
static Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
}
String message = (String)msg.obj;
Toast.makeText(s_context, message, Toast.LENGTH_SHORT).show();
}
};
}

剩下的就是在
public class Game extends Cocos2dxActivity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
JavaHelper.initContext(this);
}

基本做法就是这样只,而java调用cocos2d-x的话,后面在看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值