jni的意思是java本地调用,通过jni可以实现java层代码和其他语言写得代码进行交互。在cocos2d-x中,如果想要在c++层调用java层的代码,就是通过jni技术。通过调用java层的代码,我们就可以在Android平台下实现一些引擎没有提供给我们的功能,或者做一些其他的功能。比如加个广告,加个分享,调用Android原生的对话框等等吧。Cocos2d-x比较人性化的是为我们封装了jni调用的一些接口,这个类就是JniHelper,我们只需要使用这个类提供给我们的接口就可以完成调用java层代码的功能。先说一下这个类的位置,因为自己在找的时候有点犯二,所以特意说明一下。在3.0和3.1以上的引擎版本中,这个类的位置分别如下。
3.1以后引擎把原来cocos目录下的包含各个功能的文件夹都放到了cocos目录下,我个人认为这样的放法还是比较好的。就是引擎老改目录,希望以后不要放来放去了。最主要的当然是看看怎么使用JniHelper这个类了。
首先使用之前要包含头文件,写法如下,记住要加上条件编译,这个东西是Android平台下才用到。
1 |
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) |
3 |
#include "platform/android/jni/JniHelper.h" |
4
#include <jni.h> |
6
#endif |
接着通过一小段代码来说明一下这个类的用法。
// JNIEnv * env;
// jmethodID methodID;
8
9 |
JniMethodInfo info; |
10
11 |
|
12
bool ret = JniHelper::getStaticMethodInfo(info, "org/cocos2dx/cpp/TestJni" ,monospace!important; border:0px!important; color:blue!important; font-size:1em!important; padding:0px!important; margin:0px!important; outline:0px!important; float:none!important; vertical-align:baseline!important; position:static!important; left:auto!important; top:auto!important; right:auto!important; bottom:auto!important; height:auto!important; width:auto!important; line-height:1.1em!important; direction:ltr!important; display:inline!important; background:none!important">"func1" "()V" ); |
14
{ |
15 |
log ( "call void func1() succeed" ); |
16
//传入类ID和方法ID,小心方法名写错,第一个字母是大写 |
17 |
info.env->CallStaticVoidMethod(info.classID,info.methodID); |
18
} |
importandroid.util.Log;
publicclass
TestJni
static
void
func1()
Log.e("xiaota"
"java:func1,called succeed!"
int
func2()
return3838438
;
staticString func3(
i)
String str ="get int value:"
+i;
20
21 |
String func4(String str) |
22
23 |
24 |
str; |
26
func5(a, b) |
28
c = a+b; |