2012-03-22 101 views
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); 
}  

回答

3

使用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方法我做的方式,如果你混淆。

+0

謝謝。但是你的randRage函數不適用於我。當我運行應用程序並觸摸屏幕時,它會被「強制關閉」錯誤關閉。 – androidGirl 2012-03-23 09:58:30

+1

我的'randRange'函數缺少返回類型('int',現在已更正)和一個括號。除此之外,它工作正常。你是否已經注意到並修復了這些錯誤?如果不是,請立即嘗試。如果它仍然不起作用,那麼取消'randRange'調用,看看問題是否仍然出現,可能是別的。 – Irfy 2012-03-23 10:42:04