Random vibration duration

你离开我真会死。 提交于 2019-12-25 04:58:09

问题


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.



来源:https://stackoverflow.com/questions/9832319/random-vibration-duration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!