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?
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
or
You could also have multiple steps, allowing you to cancel mid way.