Search code examples
javaandroidmultithreadingandroid-activityrunnable

How can I use onRestart() to unpause/restart a thread in an Android Activity?


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;
        }

    }
}

Solution

  • I got it to work. I renamed my thread's pause() method to shouldStop(). I created a new thread each time in onStart(), while calling my thread's shouldStop() method each time in onStop().

    private RefreshingThread refreshingThread = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    protected void onStart(){
        super.onStart();
        refreshingThread = new RefreshingThread();
        refreshingThread.start();       
    }  
    
    @Override
    protected void onStop(){
        super.onStop();
        refreshingThread.shouldStop(); 
    }