8

Trying to use a Timer to do run this 4 times with intervals of 10 seconds each.

I have tried stopping it with a loop, but it keeps crashing. Have tried using the schedule() with three parameters, but I didn't know where to implement a counter variable. Any ideas?

final Handler handler = new Handler(); 
Timer timer2 = new Timer(); 

TimerTask testing = new TimerTask() {
    public void run() { 
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test",
                    Toast.LENGTH_SHORT).show();

            }
        });
    }
}; 

int DELAY = 10000;
for (int i = 0; i != 2 ;i++) {
    timer2.schedule(testing, DELAY);
    timer2.cancel();
    timer2.purge();
}
Sufian
  • 6,405
  • 16
  • 66
  • 120
jimmyC
  • 563
  • 1
  • 6
  • 20

3 Answers3

13
private final static int DELAY = 10000;
private final Handler handler = new Handler();
private final Timer timer = new Timer();
private final TimerTask task = new TimerTask() {
    private int counter = 0;
    public void run() {
        handler.post(new Runnable() {
            public void run() {
                Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        if(++counter == 4) {
            timer.cancel();
        }
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer.schedule(task, DELAY, DELAY);
}
Y2i
  • 3,748
  • 2
  • 28
  • 32
2

Why not use an AsyncTask and just have it Thread.sleep(10000) and the publishProgress in a while loop? Here is what it would look like:

new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {

            int i = 0;
            while(i < 4) {
                Thread.sleep(10000);
                //Publish because onProgressUpdate runs on the UIThread
                publishProgress();
                i++;
            }

            // TODO Auto-generated method stub
            return null;
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            //This is run on the UIThread and will actually Toast... Or update a View if you need it to!
            Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
        }

    }.execute();

Also as a side note, for longer term repetitive tasks, consider using AlarmManager...

Salil Pandit
  • 1,498
  • 10
  • 13
1
for(int i = 0 ;i<4 ; i++){
    Runnable  runnableforadd ;
    Handler handlerforadd ;
    handlerforadd = new Handler();
    runnableforadd  = new Runnable() {
        @Override
        public void run() {
          //Your Code Here
            handlerforadd.postDelayed(runnableforadd, 10000);                         } 
    };
    handlerforadd.postDelayed(runnableforadd, i);

}
Parag Chauhan
  • 35,760
  • 13
  • 86
  • 95