0

Here is a code which I want to repeat 50 times after every 3 seconds. if I am calling this function with 'for' loop or 'while' loop it is not working properly Please give me suggestion.

for (int i = 0; i < 50; i++) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                Generate_Ballon();
            }
        }, delay);
    }
Raghunandan
  • 132,755
  • 26
  • 225
  • 256

3 Answers3

2

You can use CountDownTimer

See Example,

new CountDownTimer(150000, 3000) 
{

     public void onTick(long millisUntilFinished) 
     {
         // You can do your for loop work here
     }

     public void onFinish() {
         mTextField.setText("done!");
     }
  }.start();

Here onTick() method will get executed on every 3 seconds.

Lucifer
  • 29,392
  • 25
  • 90
  • 143
0

You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.

private int mInterval = 5000; // 5 seconds by default, can be changed later
  private Handler mHandler;

  @Override
  protected void onCreate(Bundle bundle) {
    ...
    mHandler = new Handler();
  }

  Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
      updateStatus(); //this function can change value of mInterval.
      mHandler.postDelayed(mStatusChecker, mInterval);
    }
  };

  void startRepeatingTask() {
    mStatusChecker.run(); 
  }

  void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
  }
Bhanu Sharma
  • 5,135
  • 2
  • 24
  • 49
0
private int count = 50;
private Handler handler = new Handler();
private Runnable r = new Runnable() {
    public void run() {
        Generate_Ballon();
        if (--count > 0) {
            handler.postDelayed(r, delay);
        }
    }
};

handler.postDelayed(r, delay);
cybersam
  • 63,203
  • 6
  • 53
  • 76