随机振动持续时间 [英] Random vibration duration

查看:87
本文介绍了随机振动持续时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

请帮帮我.

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

推荐答案

使用 随机.

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 方法,如果它让你感到困惑.

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

这篇关于随机振动持续时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆