How to "kill" current runnable and start a new one pressing a start/stop android button (and prevent multiple overlapping runnable processes)?

28 views Asked by At

I am struggling with an android button to start/stop a recurrent function, but I couldn't find a suitable solution/explanation after trying to use the handler.postDelayed(), handler.removeCallbacksAndMessages() and executorService() functions.

There's a "start/stop" button which should:

  1. call a function that automatically runs every predefined seconds (with a timer also),
  2. stop the current runnable process (in order to change some inputs)
  3. start a new process (with these new inputs)
public void startAndStopButton(View v){
      final Handler myHandler = new Handler();
      final Runnable myRunnable = new Runnable() {
          public void run() {
              startTimer();
              runRandomOperation();
              myHandler.postDelayed(this, delay);
          }
      };
      myHandler.postDelayed(myRunnable, 0);
  }

At the moment, I managed to start the timer and run the recurrent function, but I still can't:

  1. kill/interrupt the current runnable (in order to stop the process, change some inputs and re-start it)
  2. prevent the overlapping of multiple runnables if the user press the button repeatedly (the timer and function calls mess up)

(I don't want to use Threads and the Sleep method, since the user should be able to change some inputs while the runnable is executing)

0

There are 0 answers