For an Android Activity, how do I stop or pause a thread on onStop()
, and then restart or unpause the thread on onRestart()
? When I start another activity on my phone, it looks like onStop()
properly stops my thread, but when I try to restart my activity, onRestart()
does not work as intended and the thread is no longer running, i.e., my views are no longer refreshing and the countdown is frozen. (Rotating my phone seems to restart the thread, i.e., the views resume refreshing and the countdown is active.)
Also, is it better that onStop()
stops your thread, or should it only pause it?
public class MyActivity extends Activity {
private static final int SLEEP_TIME = 500;
private RefreshingThread refreshingThread = new RefreshingThread();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
refreshingThread.start();
}
@Override
protected void onStop(){
super.onStop();
refreshingThread.pause();
}
@Override
protected void onRestart() {
super.onRestart();
refreshingThread.unpause();
}
private void updateViews() {
// code to update my Views, including refreshing a countdown
}
class RefreshingThread extends Thread {
private volatile boolean isPaused = false;
@Override
public void run() {
try {
while (!isInterrupted() && !isPaused) {
runOnUiThread(new Runnable() {
@Override
public void run() {
updateViews();
}
});
Thread.sleep(SLEEP_TIME);
}
} catch (InterruptedException e) {
Log.w("MyActivity", "Caught InterruptedException", e);
}
}
public void pause() {
isPaused = true;
}
public void unpause() {
isPaused = false;
}
}
}