javaandroidrunnableandroid-handlerthread

android - cancel runnable that already start running


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?


Solution

  • 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
    }