随机生成器自动随机

时间:2015-09-02 11:12:07

标签: java android random

我们知道以下代码是随机数

Random generator = new Random();
number = generator.nextInt(VALUE) + 1;

如果按钮单击

,我将此代码设为Random generator
button1 = (Button)findViewById(R.id.buttonblack);
if(v==button1) {

 // Here, we are generating a random number
 Random generator = new Random();
 number = generator.nextInt(5) + 1; 
 // The '5' is the number of values

 // Here, we are checking to see what the output of the random was
 switch(number) { 

     case 1: if(bla.. bla.. bla.. == 1){
             //Do some blaa. blaa. blaa. logic
         }
        else if(bla.. bla.. bla.. == 2){
             //Do some blaa. blaa. blaa. logic
         }
         break;
       //and so on..

我的问题是如何使Random Generator方法每2秒自动随机一次然后越来越快,而不是单击按钮

以及如果点击某个按钮,如何随机停止,例如

buttonstop = (Button)findViewById(R.id.buttonstop);    
buttonstop.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v){ 

            //Stop Random generator  

        }
     });

任何人都可以回答?感谢的

1 个答案:

答案 0 :(得分:1)

使用它从2秒开始加快20毫秒

  private Handler mHandler = new Handler();
    int ms=2000; //2secs.
    Define a Runnable:

    private Runnable mUpdateTimeTask = new Runnable() {
        public void run() {
            // get random number here

        // You could do this call if you wanted it to be periodic:

    ms=ms-20; //20ms faster
            mHandler.postDelayed(this, ms);

            }
        };

    mHandler.postDelayed(mUpdateTimeTask, 100);