Android Unable to cancel Vibration via VIBRATOR_SERVICE cancel()

262 Views Asked by At

Info: Android Compiled SDK 33 Device: Pixel 6

Issue: I am having trouble using the VIBRATOR_SERVICE. All I would like to do is cancel and active vibration while its running, and start a new vibrate command (with a different intensity/duration)

Examples:

  1. As you would expect, this code vibrates my device for 1 second:
// create vibrator instance
Vibrator vib = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_GAME)
    .build();

// vibrate for 20 seconds (unless cancelled)
vib.vibrate(20000, audioAttributes);

// wait 1 second and then cancel the vibrator
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        Log.e("TAG", "Cancel Vibration");
        vib.cancel();
    }
}, 1000);
  1. Now here is the issue. This code vibrates my device for 20 seconds. Why doesn't this vibrate the device for 1 second?
// create vibrator instance
Vibrator vib = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
    .setUsage(AudioAttributes.USAGE_GAME)
    .build();

// vibrate for 20 seconds (unless cancelled)
vib.vibrate(20000, audioAttributes);

// ============== NEW CODE HERE ================
vib.cancel(); // cancel the active vibration at any point
vib.vibrate(20000, audioAttributes); // start a new vibrate command
// =============== END NEW CODE ================

// wait 1 second and then cancel the vibrator
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        Log.e("TAG", "Cancel Vibration");
        vib.cancel();
    }
}, 1000);

What am I missing here? What is the correct way to cancel the active vibration and start a new one? The first time I cancel it, I appear to lose the ability to cancel any future vibrate commands. Hoping this is something simple that I am missing, thanks for the help!

1

There are 1 best solutions below

2
sumit On
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
    //deprecated in API 26 
    v.vibrate(500);
}

v.cancel();//For stop vibrator