6

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-generated method stub
    //while (running) {
     mUpdateTime = new Runnable() {
            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);
            }
        };
        mHandler.postDelayed(mUpdateTime, 1000);
    //}

now i want to stop that runnable on pause button click

pause_btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            play_btn.setVisibility(View.VISIBLE);
            pause_btn.setVisibility(View.INVISIBLE);

        }
    });

How can i stop that runnable on pause button click if anyone knows please help me.

Raj
  • 844
  • 2
  • 11
  • 29
  • 1
    Possible duplicate of [Android: How do I stop Runnable?](http://stackoverflow.com/questions/9458097/android-how-do-i-stop-runnable) – patryk.beza May 12 '16 at 09:52

5 Answers5

15

Use

mHandler.removeCallbacksAndMessages(runnable);

in pause button click.

Raj
  • 844
  • 2
  • 11
  • 29
Arun C
  • 9,035
  • 2
  • 28
  • 42
9

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.

rai.skumar
  • 10,309
  • 6
  • 39
  • 55
  • 1
    AFAIK, this is the best method for shutting down an asynchronous operation. It isn't free (the operation has to poll the flag) but it allows the operation to end a) in its own time and b) clean up all its resources. The method I see too often is just aborting a thread - a very dangerous practice. By all means, inherit your own Runnable and declare this flag for reuse! – Gusdor Apr 24 '13 at 09:43
  • There are no issues if you share nothing (no primitive types, objects, etc) between threads, and cleanup when you stop. – stephen Sep 07 '13 at 06:37
1

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

Use below code :

handler.removeCallbacks(runnable);
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44
Arda Kaplan
  • 1,720
  • 1
  • 15
  • 23
-2

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();
Sharad Mhaske
  • 1,103
  • 9
  • 19
  • 1
    What could be the purpose of using a Runnable inside a Thread in your example other than answering the question? – Bart Burg Jan 07 '15 at 09:32