希望这篇文章能够给大家带来帮助废话少说直接在COCOS2D-X自带的HelloCpp中添加代码如下:
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "jni/JniHelper.h"
#endif
bool HelloWorld::init()
{
CCLayer::init();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
const char* pStr = "Cpp Call Java Function!!!";
JniMethodInfo MethodInfo;
bool BExist
= JniHelper::getStaticMethodInfo(MethodInfo,"mm/nn/oo/HelloCpp","ShowMessageFromNative","(Ljava/lang/String;)V");
if (BExist)
{
jstring Str = MethodInfo.env->NewStringUTF(pStr);
MethodInfo.env->CallStaticVoidMethod(MethodInfo.classID,MethodInfo.methodID,Str);
MethodInfo.env->DeleteLocalRef(Str);
MethodInfo.env->DeleteLocalRef(MethodInfo.classID);
}
#endif
return true;
}
然后我们修改MK文件在相应的地方分别加上如下语句:
LOCAL_WHOLE_STATIC_LIBRARIES += PluginProtocolStatic
$(call import-moudle,plugin/protocols/proj.android/jni)
我们Android中的代码看起来是这样的(只显示我们这里需要关注的)
package mm.nn.oo;
public class HelloCpp extends Cocos2dxActivity
{
public static Activity mContext;
static Handler Statichandler = new Handler()
{
@Override public void handleMessage(Message msg)
{
switch (msg.what)
{
case 1:
String StrMsg = (String)msg.obj;
Toast.makeText(mContext,StrMsg,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
};
};
public static void ShowMessageFromNative(String str)
{
Message msg = new Message();
msg.what = 1;
msg.obj = str;
Statichandler.sendMessage(msg);
}
最后附上本工程下载地址
http://t.cn/8sPuK2J那就说到这里了拜拜
![再见](http://static.blog.csdn.net/xheditor/xheditor_emot/default/bye.gif)