COCOS2D-X之CPP調用Android函數Demo

希望這篇文章能夠給大傢帶來幫助廢話少說直接在COCOS2D-X自帶的HelloCpp中添加代碼如下:

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
 #include 
 #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);
 }

最後附上本工程下載地址https://t.cn/8sPuK2J那就說到這裡瞭拜拜再見

本人鄭重聲明如下 一、本文來自CSDN博客,傳送門:https://BlOG.CSDN.NET/yirancpp 二、All Rights Reserved. 任何個人或網站轉載本文時不得移除本聲明. 三、不得對文章進行修改,除非明確說明.同時歡迎大傢評論轉載和分享.

發佈留言