How to pause/resume thread in Android?
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();
}
}
}
Try the below code it will work
Thread thread=null;
OnResume()
public void onResume(){
super.onResume();
if(thread == null){
thread = new Thread()
{
@Override
public void run() {
try {
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
}
onPause()
@Override
public void onPause(){
super.onPause();
if(thread != null){
Thread moribund = thread;
thread = null;
moribund.interrupt();
}
}