cpp部分通过jni调用java静态函数
头文件:
#include <jni.h> #include "cocos2d.h" #include "platform/android/jni/JniHelper.h"
在cpp类中定义方法去调用Cocos2dxSound.java中vibrate方法:
static void vibrateJNI(long longtime) { JniMethodInfo methodInfo; if(!JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxSound", "vibrate","(J)V")) { CCLOG("Error: vibrate is 不存在!"); return; } methodInfo.env->CallStaticVoidMethod(methodInfo.classID,methodInfo.methodID,time); methodInfo.env->DeleteLocalRef(methodInfo.classID); }
在android工程src/org/cocos2dx/lib/Cocos2dxSound.java定义vibrate方法:
private static Context mContext2;
Cocos2dxSound()方法中加入
this.mContext2 = pContext;
定义vibrate方法
public static void vibrate(long time) { Vibrator v = (Vibrator) mContext2.getSystemService(Context.VIBRATOR_SERVICE); v.vibrate(time); }
致此在cpp代码中需要震动处调用以下即可
JNIUtil::vibrateJNI(500);