简体   繁体   中英

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?

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.

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

使用下面的代码

handler.removeCallbacksAndMessages(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM