Cocos2d-x通过JNI实现Android端的震动

首先看Android端的实现:

package com.cocos2dx.MyJni;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;

public class MyJni extends Cocos2dxActivity {

	public static MyJni actInstance;// 定义单例

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		actInstance = this;
	}

	public Cocos2dxGLSurfaceView onCreateView() {
		Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
		glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
		return glSurfaceView;
	}

	public static void vibrate(long time)
	{
		Log.v("vibrate","time="+time);
		// 获取Vibrate对象
		Vibrator vibrator = (Vibrator)actInstance.getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(time);
	}

	static {
		System.loadLibrary("cocos2dcpp");
	}
}

记着在AndroidManifest.xml里面加入震动权限

<uses-permission android:name="android.permission.VIBRATE"/>

Cocos2d-x端实现:

MyJniHelper.h

#ifndef __H_MYJNIHELPER_H__
#define __H_MYJNIHELPER_H__
#include "cocos2d.h"
USING_NS_CC;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <jni.h>
#include "platform/android/jni/JniHelper.h"
#define  CLASS_NAME "com.cocos2dx.MyJni.MyJni"
#endif
class MyJniHelper {
public:
	MyJniHelper();
	~MyJniHelper();
	static void vibrate(long time);
};

#endif

MyJniHelper.cpp

#include "MyJniHelper.h"

void MyJniHelper::vibrate(long time)
{
#if(CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
	JniMethodInfo t;
	if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "vibrate", "(J)V"))
	{
		jlong _time = time;
		t.env->CallStaticVoidMethod(t.classID, t.methodID,_time);
		t.env->DeleteLocalRef(t.classID);
	}
#endif
}

需要使用震动的地方,这样使用

MyJniHelper::vibrate(500L);

参数为震动持续的时间