0

我使用这个 android 代码,当用户触摸屏幕时,振动开始并持续 3000 毫秒。我不希望用户总是触摸屏幕,振动的持续时间与以前的时间(3000 毫秒)相同。我想使用随机的,每次振动持续随机的时间。我应该如何根据我的代码使用随机数?

请帮我。

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);   
}    
4

1 回答 1

3

使用Random

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);
}

如果它让您感到困惑,请参阅文档Random.nextInt(int)以了解为什么我以我randRange的方式编写该方法。

于 2012-03-23T00:06:31.660 回答