3

I'm using a postDelayed runnable thread, I need to pause and resume that thread when I press a button. Please anyone help me on that.

This is my thread:

    protected void animation_music6() {
    music4.postDelayed(new Runnable() {
        public void run() {
              music4.setVisibility(View.VISIBLE);
            animationmusic4();
            holemusic4();

        }
    }, 10000);
}

I need to pause the thread when i press a button and resume from where i pause the thread. I have used to pause the thread is:

music4.removeCallbacks(runnable4);

How i can resume the thread? Can anyone please help me. Is there any way to pause and resume the thread? I am a new to the android, So please help me to do this. Thanks in Advance.

user2425850
  • 51
  • 2
  • 6

2 Answers2

6

I apologize for the poor formatting

 boolean isPaused = true;

 playButton.setOnClickListener(new OnClickListener() { 
     public void onClick(View v) { 
        isPaused = !isPaused;
        if(isPaused) { 
            music4.removeCallbacks(runnable4);
        }
        else { 
            music4.postDelayed(runnable4, 100);
        }
     }
});
ductran
  • 10,043
  • 19
  • 82
  • 165
Ryan D'souza
  • 653
  • 11
  • 22
2

I have a similar issue that I am confused about. As taught here I'm using postDelayed() to have a Runnable start after a delay, let´s say after 4 seconds. I want to implement a pause function so that if I pause, and at that point in time there for example is 2 seconds left until the runnable code was supposed to start, then when I later resume I want the delay to resume at the exact point in time where it became paused, so that the postDelayed operation will continue and will have the thread run 2 seconds after I resume. A kind of timer freeze()/unfreeze() operation. Will I need to use timers to accomplish that ?

  • Comm enting on my own question some years later... What I was working on was a 'scene player' that executes a timeline of events. And in the midst of all those scene events about to play out at any time I want to pause progress and be able to resume exactly where I paused. The solution is to implement what's missing. Instead of a regular thread I create a class 'PauseThread' that adds the extra pause feature. Underneath the hood it works with regular threads and timers to accomplish the perceived experience of a 'pausable' thread, I won't go into the details but you may get some sense of it. – Gunnar Forsgren - Mobimation Oct 08 '19 at 17:24
  • Hey, as your comment, i am also trying to create a thread that could be paused/resumed. i have been searching for this for a long time. can you shed light on how you did that? – ansh sachdeva Apr 12 '20 at 09:50