How to Suspend and Resume Threads in android?
Asked Answered
T

1

6

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?

Tridentum answered 17/4, 2012 at 10:15 Comment(2)
how about service: developer.android.com/guide/topics/fundamentals/services.htmlBackground
Hi LeoLink I dont think services would sort my problem. thanks anywyays :)Tridentum
R
7

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();
     }
}
Respective answered 17/4, 2012 at 10:22 Comment(2)
Oh ok I understand it now @Tudor. btw another clarification is this similar to signalling in threads?Tridentum
@rosesr: It is similar to condition variables in linux for example.Respective

© 2022 - 2024 — McMap. All rights reserved.