Why the VibrationEffect is not working on Samsung devices only

159 Views Asked by At

I'm trying to make a vibration effect using the below code :

public static void vibrate(Context context) {
        if (context != null) {
            if (SPUtils.getInstance().getBoolean("isVibrationOn", true)) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                if (vibrator.hasVibrator()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                            VibrationEffect vibrationEffect = VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK);
                            vibrator.vibrate(vibrationEffect);
                        } else
                            vibrator.vibrate(VibrationEffect.createOneShot(15, VibrationEffect.CONTENTS_FILE_DESCRIPTOR));
                    } else vibrator.vibrate(15);
                }
            }
        }
    }

For some reason, the vibration is not working on all tested Samsung devices, such as:

  • Samsung Galaxy A13
  • Samsung Galaxy A32
  • Samsung Galaxy A20

I wonder if the Samsung device needs some additional code to make the vibration work.

1

There are 1 best solutions below

2
Hatem Darwish On

Ensure that your app has the necessary permissions to vibrate the device. You need to include the

<uses-permission android:name="android.permission.VIBRATE" /> 

permission in your app's AndroidManifest.xml file.

Double-check your code to make sure you're creating and applying the VibrationEffect correctly. Here's an example of how to create and use a VibrationEffect: try use createOneShot

Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator != null && vibrator.hasVibrator()) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        VibrationEffect vibrationEffect = VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE);
        vibrator.vibrate(vibrationEffect);
    } else {
        // For devices before Android Oreo (API level 26)
        vibrator.vibrate(1000);
    }
}