简体   繁体   中英

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, ie, my views are no longer refreshing and the countdown is frozen. (Rotating my phone seems to restart the thread, ie, 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;
        }

    }
}

Change this method:

@Override
protected void onRestart() {
    super.onRestart();
    refreshingThread.unpause();
}

To:

@Override
protected void onStart() {
    super.onStart();
    refreshingThread.start();   <-- remove from onCreate();
}

With this you will always start the thread when your activity starts up (or restarts) and stop it when your Activity is stopped.

First, it is advised that refreshing data will be done by pushing new data from the server rather than pulling it - this will help saving battery, bandwidth and being more efficient in general. you can use GCM to push data, for example check: http://www.doubleencore.com/2013/09/push-dont-poll-how-to-use-gcm-to-update-app-data/

If you still prefer pulling data once every X seconds (SLEEP_TIME), I would suggest you'll use a Timer, which can be scheduled to run a TimerTask every X seconds. you can then cancel/restart it from onPause/onResume. Example:

public class RefreshManager {
    private static Timer timer = null;
    private RefreshTimerTask refreshTask;

    public void onResume() {
        this.start(INIT_DELAY_TIME);
    }

    public void onPause() {
        this.stop();
    }

    private void start(long delay) {
        stop(); // stop any older timer instance if exist.
        timer = new Timer();
        refreshTask = new RefreshTimerTask();
        timer.schedule(refreshTask, delay, SLEEP_TIME);
    }

    private void stop() {
        if (timer != null) {
            timer.cancel();
            refreshTask = null;
            timer = null;
        }
    }

    private class RefreshTimerTask extends TimerTask {
        @Override
        public void run() {
            updateViews();
        }
    }
}

You should create a RefreshManager instance and call it's onResume and onPause on the activity onPause/onResume.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM