diff --git a/templates/android/template/app/src/main/java/org/haxe/lime/GameActivity.java b/templates/android/template/app/src/main/java/org/haxe/lime/GameActivity.java index e0c37f44c..3c28d7a6c 100644 --- a/templates/android/template/app/src/main/java/org/haxe/lime/GameActivity.java +++ b/templates/android/template/app/src/main/java/org/haxe/lime/GameActivity.java @@ -8,6 +8,7 @@ import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; +import android.os.VibrationEffect; import android.os.Vibrator; import android.util.DisplayMetrics; import android.util.Log; @@ -29,10 +30,10 @@ public class GameActivity extends SDLActivity { private static AssetManager assetManager; private static List extensions; private static DisplayMetrics metrics; + private static Vibrator vibrator; public Handler handler; - public static double getDisplayXDPI () { if (metrics == null) { @@ -109,6 +110,7 @@ public class GameActivity extends SDLActivity { super.onCreate (state); assetManager = getAssets (); + vibrator = (Vibrator)mSingleton.getSystemService (Context.VIBRATOR_SERVICE); handler = new Handler (); Extension.assetManager = assetManager; @@ -176,6 +178,12 @@ public class GameActivity extends SDLActivity { @Override protected void onPause () { + if (vibrator != null) { + + vibrator.cancel (); + + } + super.onPause (); for (Extension extension : extensions) { @@ -370,25 +378,47 @@ public class GameActivity extends SDLActivity { public static void vibrate (int period, int duration) { - Vibrator v = (Vibrator)mSingleton.getSystemService (Context.VIBRATOR_SERVICE); + if (vibrator == null || !vibrator.hasVibrator () || period < 0 || duration <= 0) { + + return; + + } if (period == 0) { - v.vibrate (duration); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + + vibrator.vibrate (VibrationEffect.createOneShot (duration, VibrationEffect.DEFAULT_AMPLITUDE)); + + } else { + + vibrator.vibrate (duration); + + } } else { - int periodMS = (int)Math.ceil (period / 2); - int count = (int)Math.ceil ((duration / period) * 2); + // each period has two halves (vibrator off/vibrator on), and each half requires a separate entry in the array + int periodMS = (int)Math.ceil (period / 2.0); + int count = (int)Math.ceil (duration / (double) periodMS); long[] pattern = new long[count]; - for (int i = 0; i < count; i++) { + // the first entry is the delay before vibration starts, so leave it as 0 + for (int i = 1; i < count; i++) { pattern[i] = periodMS; } - v.vibrate (pattern, -1); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + + vibrator.vibrate (VibrationEffect.createWaveform (pattern, -1)); + + } else { + + vibrator.vibrate (pattern, -1); + + } }