user3509871
user3509871

Reputation: 17

Repeat a Method for specific times in android

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

Upvotes: 0

Views: 1793

Answers (3)

cybersam
cybersam

Reputation: 67019

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

Upvotes: 0

Lucifer
Lucifer

Reputation: 29672

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.

Upvotes: 2

Bhanu Sharma
Bhanu Sharma

Reputation: 5145

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

Upvotes: 0

Related Questions