Article: Vibration implementation for Android API level 26 up

Just to add on top of this particular post about implementing vibration in Android.
For Android API level 26 and up, just the vibrate(duration) method won’t work as it’s deprecated.

Do the following to fix that:

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

// Import these libraries
import android.content.Context;
import android.os.Build;
import android.os.Vibrator;
import android.os.VibrationEffect;

public class AppActivity extends CocosActivity {
    // declare variable 
    public static Vibrator nativeVibrator;

    protected void onCreate(Bundle savedInstanceState) {
        // Initialize this variable
        nativeVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        // existing stuff


    // declare method
    public static void vibrate(int duration){
      try {
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
              nativeVibrator.vibrate(VibrationEffect.createOneShot(duration, VibrationEffect.DEFAULT_AMPLITUDE));
          } else {
      }catch (Exception e){

At AndroidManifest.xml file:
(Path: /native/engine/android/app/)

    // Add this to provide permission
    <uses-permission android:name="android.permission.VIBRATE"/>

Hope this helps someone

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