How to stop Runnable on button click in Android?

前端 未结 5 1494
野趣味
野趣味 2020-12-11 18:44

I have to start runnable on start button click and stop it on pause button click. My code for start runnable on start button click is

    // TODO Auto-gener         


        
5条回答
  •  春和景丽
    2020-12-11 19:19

    Keep a boolean cancelled flag to store status. Initialize it to false and then modify it to true on click of stop button.

    And inside your run() method keep checking for this flag.

    Edit

    Above approach works usually but still not the most appropriate way to stop a runnable/thread. There could be a situation where task is blocked and not able to check the flag as shown below:

         public void run(){
            while(!cancelled){
               //blocking api call
            }
        }
    

    Assume that task is making a blocking api call and then cancelled flag is modified. Task will not be able to check the change in status as long as blocking API call is in progress.

    Alternative and Safe Approach

    Most reliable way to stop a thread or task (Runnable) is to use the interrupt mechanism. Interrupt is a cooperative mechanism to make sure that stopping the thread doesn't leave it in an inconsistent state.
    On my blog, I have discussed in detail about interrupt, link.

提交回复
热议问题