Skip to content Skip to sidebar Skip to footer

How To Stop A Timer After Certain Number Of Times

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 th

Solution 1:

privatefinalstaticintDELAY=10000;
privatefinalHandlerhandler=newHandler();
privatefinalTimertimer=newTimer();
privatefinalTimerTasktask=newTimerTask() {
    privateintcounter=0;
    publicvoidrun() {
        handler.post(newRunnable() {
            publicvoidrun() {
                Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show();
            }
        });
        if(++counter == 4) {
            timer.cancel();
        }
    }
};

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timer.schedule(task, DELAY, DELAY);
}

Solution 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>() {

        @OverrideprotectedVoid 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 stubreturnnull;
        }
        @Overrideprotected 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...

Solution 3:

for(int i = 0 ;i<4 ; i++){
    Runnable  runnableforadd ;
    Handler handlerforadd ;
    handlerforadd = new Handler();
    runnableforadd  = new Runnable() {
        @Override
        publicvoidrun() {
          //Your Code Here
            handlerforadd.postDelayed(runnableforadd, 10000);                         } 
    };
    handlerforadd.postDelayed(runnableforadd, i);

}

Post a Comment for "How To Stop A Timer After Certain Number Of Times"