1

I have a long process in the background to do. So onCreate, I post a runnable in my handler from handlerThread but I have a button that allows users to cancel it. It's possible to stop a Runnable after it starts?

@Override
protected void onCreate(Bundle savedInstanceState) {
    Handler h = new Handler( HandlerThread.getLooper() );
    Runnable runnable = //class that implements runnable;

    h.post( runnable );

    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            h.removeCallbacks(runnable);
        }
    }
}

but it seems that doesn't cancel runnable that already running, Or should I use postDelayed() with a huge delay?

ola
  • 35
  • 3

2 Answers2

0

Inside of your runnable have a boolean flag for running.

Your button then can set this flag to true/false, to stop it running.

You can implement pause, resume, or start, stop, it all depends on your usecase.

i.e. something like

while(running) {
   // Your repeated background code
}

or

if(running) {
   // do some one shot code, i.e. the user can stop it if they press the button before the if, but not after. 
}

You could also have multiple steps, allowing you to cancel mid way.

if(running) {
  // do step 1 code
}
if(running) {
  // do step 2 code
}
Blundell
  • 75,855
  • 30
  • 208
  • 233
0

Use below code

handler.removeCallbacksAndMessages(null);
  • this cancels all the runnings, so that might cancel running that I want to keep running – ola Aug 24 '20 at 09:56