【问题标题】:Random vibration duration随机振动持续时间
【发布时间】:2012-04-07 14:33:55
【问题描述】:

我使用这个 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);   
}    

【问题讨论】:

    标签: android random vibration


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。但是你的 randRage 函数对我不起作用。当我运行应用程序并触摸屏幕时,它会因“强制关闭”错误而关闭。
    • 我的 randRange 函数缺少返回类型(int,现已更正)和括号。除此之外,它工作正常。您是否已经注意到并修复了这些错误?如果没有,请立即尝试。如果还是不行,那就去掉randRange调用,看看问题是否依然出现,可能是别的原因。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2017-01-31
    • 1970-01-01
    • 2022-12-12
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多