1.在 Classes目錄創(chuàng)建Test.h 和Test.cpp
Test.h:
#ifndef _Test_
#define _Test_
#include "cocos2d.h"
#ifndef _Test_
#define _Test_
#include "cocos2d.h"
class Test
{
public:
Test();
~Test();
};
#endif // !_Test_
Test.cpp:
#include "Test.h"
USING_NS_CC;
using namespace std;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#include <android/log.h>
extern "C" //org.cocos2dx.javascript
{
JNIEXPORT void JNICALL Java_org_cocos2dx_javascript_MyHelper_myFunc(JNIEnv *env, jobject thiz, jint m)
{
log("myFunc called!");
}
};
注釋:
1.Java_org_cocos2dx_javascript_MyHelper_myFunc: ”Java”固定開頭 ”org_cocos2dx_javascript”為包名 ”MyHelper”為對應的java文件 ”myFunc”為對應的方法 使用”_”連接
2.(JNIEnv *env, jobject thiz, jint m) 前兩個為自帶參數(shù)憎蛤,第三個m是自定義的參數(shù)
#endif
Test::Test()
{
}
Test::~Test()
{
}
- 在org/cocos2dx/javascript 新建MyHelper.java:
MyHelper.java內容:
package org.cocos2dx.javascript;
public class MyHelper {
/**
* 這里是java調用cocos2d-x的地方
* @param m
*/
public static native void myFunc(int m); //native 方法
}
3.在同目錄下AppActivity.java內調用如下:
public class AppActivity extends Cocos2dxActivity {
static { System.loadLibrary("cocos2djs"); } //調用前加上這句
@Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
// TestCpp should create stencil buffer
glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
MyHelper.myFunc(100); //此處調用
return glSurfaceView;
}
}
- 在android.mk 加上自己的cpp文件Test.cpp:
LOCAL_SRC_FILES := hellojavascript/main.cpp \
../../../Classes/AppDelegate.cpp \
../../../Classes/Test.cpp
正確運行后可以看到成功調用日志想诅。