Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 870
rosesr Avatar asked Apr 17 '12 10:04

rosesr


1 Answers

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();
     }
}
like image 199
Tudor Avatar answered Sep 18 '22 21:09

Tudor