CocosCreator系列——与Java原生交互获取手机震动

CocosCreator系列——与Java原生交互获取手机震动


首先是客户端代码

// 此方法可以绑定在一个按钮上或者某个方法里面调用
onDoVibrate() {
        jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "DoVibrate", "()V");
    },

js调用Java代码方法可以参考:Java原生反射机制可以参考官方文档链接.
如果是新手的话,官方文档说的org.cocos2dx.javascript路径要在项目构建之后,在项目根目录的build文件夹下面
下一步打开org.cocos2dx.javascript文件路径下的AppActivity.java文件编辑代码
1.导入文件所需依赖包

import android.os.Vibrator;
import android.app.Service;

2.声明静态变量myVibrator

public static Vibrator myVibrator;

3.在onCreate()方法中注册服务

myVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);

4.写手机震动方法(注意此方法要和客户端调用方法名一致)

//1000是震动毫秒数,根据自己实际需求来写值
public static void DoVibrate() { myVibrator.vibrate(1000);}

5.打开AndroidManifest.xml文件注册服务

//1000是震动毫秒数,根据自己实际需求来写值
<uses-permission android:name="android.permission.VIBRATE"/>

至此全部完成,只需要客户端调用onDoVibrate()方法,即可实现震动效果
下面附上AppActivity.java参考代码


package org.cocos2dx.javascript;

import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;
import android.os.Bundle;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Vibrator;
import android.app.Service;

public class AppActivity extends Cocos2dxActivity {

    public static Vibrator myVibrator;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            // so just quietly finish and go away, dropping the user back into the activity
            // at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }
        // DO OTHER INITIALIZATION BELOW
        SDKWrapper.getInstance().init(this);
        
        myVibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
        
    }

    public static void DoVibrate() {
        myVibrator.vibrate(1000);
    }

}

你可能感兴趣的:(CocosCreator,java,javascript)