Implementing Vibration in Cocos creator Native

Hello,
@StudioAMK, @slackmoehrle

Did anyone try this [Creator 2.1.x] Vibrate
Can someone please guide for Cocos Creator 3.3.2 for the same.
I’m have very little experience on Native platform at the moment

Hi

We have done it before.

Basically,

  • create native static method
  • call it from JS/TS

I will share you some codes when I got more time

1 Like

Please do thank you very much.

At AppActivity.java file:
(Path: /native/engine/android/app/src/com/cocos/game/)

// import library
import android.os.Vibrator;

public class AppActivity extends CocosActivity {

    // declare variable 
    public static Vibrator samkVibrator;
    
    // declare method
    public static void vibrate(int duration){
        try {
            if (samkVibrator.hasVibrator()){
                samkVibrator.vibrate(duration);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

Then in your file.ts:

    // create function
    public static vibrate(durationInMilisecond: number) {
        if (sys.isNative && sys.os === sys.OS.ANDROID) {
            jsb.reflection.callStaticMethod("com/cocos/game/AppActivity", "vibrate", "(I)V", durationInMilisecond);
        }
    }
1 Like

@StudioAMK ,

I am really gratefully to you for helping me out with this.
Thanks a ton my friend.

1 Like

@StudioAMK,

I have a follow up question related to this.
Can we add any complex task here if the same task takes more time to execute in Javascript?

As per my understanding, as long as it’s a public static method in Java, you can execute/call it in JS.

P.S. glad that my codes help! :blush:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.