2

im trying to vibrate device and repeat this pattern for 3 times so in total 6x vibrations. Im using code bellow but my device keeps vibrating infinitely. How to stop vibrating after those 3 repeats?

private void deviceVibration (){
   
   long[] pattern = {0, 2000, 1000, 2000,1000};
   vibrator.vibrate(pattern,3);

}
zon1k
  • 87
  • 7

3 Answers3

2

According to the Vibrator Documentation

public void vibrate (long[] pattern, int repeat)

This long[] pattern is an array of longs of times for which to turn the vibrator on or off. This int repeat is the index into pattern at which to repeat, or -1 if you don't want to repeat.

So if you put the 3 it will repeat the 3 index position of your pattern.

long[] pattern = {0, 2000, 1000, 2000,1000}; <-- 2000 will be repeated

So the pattern is ok, you need to remove one to just vibrate three times and then just change your 3 for -1 to don't repeat.

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • 1
    so if i change index 0 in pattern to 3 `long[] pattern = {3, 2000, 1000, 2000,1000};` and set `vibrator.vibrate(pattern,0);` it should repeat only 3 times right? – zon1k Sep 17 '21 at 13:29
0

you can try this

long[] pattern = {0, 2000, 1000, 2000,1000};
 vibrator.vibrate(pattern, -1);

-1 for to vibrate only as mentioned in the pattern.

CodeWithVikas
  • 1,105
  • 9
  • 33
0

Your code should like this

long[] pattern = {0, 2000, 1000, 2000,1000, 2000,1000};
vibrator.vibrate(pattern, -1);

As Skizo-ozᴉʞS said accept his answer it is more perfect

Usama Altaf
  • 90
  • 1
  • 4
  • 23