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 AppActivity.java 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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(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 {
nativeVibrator.vibrate(duration);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
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