COCOS2D-X之CPP调用Android函数Demo

希望这篇文章能够给大家带来帮助废话少说直接在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那就说到这里了拜拜 再见
本人郑重声明如下 一、本文来自CSDN博客,传送门:http://BlOG.CSDN.NET/yirancpp 二、All Rights Reserved. 任何个人或网站转载本文时不得移除本声明. 三、不得对文章进行修改,除非明确说明.同时欢迎大家评论转载和分享.
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页