How to stop Runnable on button click in Android?

前端 未结 5 1470
野趣味
野趣味 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:03

    Complete Code:

       iterationCount = 0;
       final Handler handler = new Handler();
        final int delay = 1000; //milliseconds
        handler.postDelayed(new Runnable() {
            public void run() {
                //do something
                if (iterationCount < 10) {
                    handler.postDelayed(this, delay);
                }
                iterationCount++;
                Log.e("tag", "after 1 second: " + iterationCount);
            }
        }, delay);
    
    0 讨论(0)
  • 2020-12-11 19:09

    Thread thread;
    //inside start button

     thread=new Thread(new Runnable() {
    
        @Override
        public void run() {
        sec += 1;
            if(sec >= 60) {
                 sec = 0;
                 min += 1;
                if (min >= 60) {
                    min = 0;
                    hour += 1;
            }
             }
             Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec));
             mHandler.postDelayed(mUpdateTime, 1000);
          });
       thread.start();
    

    //inside stop button

    mHandler.removeCallbacksAndMessages(runnable);
    thread.stop();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 19:20

    Use

    mHandler.removeCallbacksAndMessages(runnable);
    

    in pause button click.

    0 讨论(0)
  • 2020-12-11 19:29

    Use below code :

    handler.removeCallbacks(runnable);
    
    0 讨论(0)
提交回复
热议问题