I have a thread that running into an activity. I don't want that the thread continuos running when the user click the home button or, for example, the user receive a call phone. So I want pause the thread and resume it when the user re-opens the application. I've tried with this:
protected void onPause() { synchronized (thread) { try { thread.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } super.onPause(); } protected void onResume() { thread.notify(); super.onResume(); }
It stops the thread but don't resume it, the thread seems freezed.
I've also tried with the deprecated method Thread.suspend()
and Thread.resume()
, but in this case into Activity.onPause()
the thread doesn't stop.
Anyone know the solution?
Methods Used:sleep(time): This is a method used to sleep the thread for some milliseconds time. suspend(): This is a method used to suspend the thread. The thread will remain suspended and won't perform its tasks until it is resumed. resume(): This is a method used to resume the suspended thread.
As your activity enters the paused state, the system calls the onPause() method on your Activity , which allows you to stop ongoing actions that should not continue while paused (such as a video) or persist any information that should be permanently saved in case the user continues to leave your app.
sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
We all know that the threading module can implement multi-threading in python, but the module does not provide methods for suspending, resuming and stopping threads. Once the thread object calls the start method, it can only wait until the corresponding method function is completed.
Use wait()
and notifyAll()
properly using a lock.
Sample code:
class YourRunnable implements Runnable { private Object mPauseLock; private boolean mPaused; private boolean mFinished; public YourRunnable() { mPauseLock = new Object(); mPaused = false; mFinished = false; } public void run() { while (!mFinished) { // Do stuff. synchronized (mPauseLock) { while (mPaused) { try { mPauseLock.wait(); } catch (InterruptedException e) { } } } } } /** * Call this on pause. */ public void onPause() { synchronized (mPauseLock) { mPaused = true; } } /** * Call this on resume. */ public void onResume() { synchronized (mPauseLock) { mPaused = false; mPauseLock.notifyAll(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With