rosesr
rosesr

Reputation: 789

How to Suspend and Resume Threads in android?

I just noticed that suspend and resume in android threading has been deprecated. What is the work around for this or how can I suspend and resume a thread in android?

Upvotes: 6

Views: 5692

Answers (1)

Tudor
Tudor

Reputation: 62439

Indeed, suspending or stopping threads at random points is an unsafe idea, which is why these methods are deprecated.

The best you can do in my opinion is to have fixed points of pausing in your thread's run method and stopping there using wait:

class ThreadTask implements Runnable {

     private volatile boolean paused;
     private final Object signal = new Object();

     public void run() {
         // some code

         while(paused) { // pause point 1
            synchronized(signal) signal.wait();
         }

         // some other code

         while(paused) { // pause point 2
            synchronized(signal) signal.wait();
         }

         // ...
     }

     public void setPaused() {
         paused = true;      
     }

     public void setUnpaused() {
         paused = false;
         synchronized(signal) signal.notify();
     }
}

Upvotes: 7

Related Questions