-->

Random vibration duration

2019-08-20 17:19发布

问题:

I used this android code that when a user touch a screen, vibration is started and continued for 3000 ms. I don't want that always that user touch the screen, the duration of the vibration become the same as previous times(3000 ms). I want to use random that each time the vibration lasts for a random amount of time. How should I use random according to my code?

Please help me.

public boolean dispatchTouchEvent(MotionEvent ev) 
{    
   if (ev.getAction() == MotionEvent.ACTION_UP)
   {    
      Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    
      v.vibrate(3000);    
   }    
   return super.dispatchTouchEvent(ev);   
}    

回答1:

Use the Random class.

private Random rnd = new Random();

private int randRange(int min, int max) {
    return min + rnd.nextInt(max - min);
}

public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_UP) {
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(randRange(min, max)); // integer variables of your choice
    }
    return super.dispatchTouchEvent(ev);
}

See the documentation of Random.nextInt(int) to understand why I wrote the randRange method the way I did, if it confuses you.