Search code examples
androidrunnable

Runnable stopped when activity is paused


I have a clock done by updating a TextView text using a Runnable. When I'm in the Activity the TextView is updated properly, but when I leave and come back to the activity, the code in the run() method is not executed anymore.

Do I have to call run() again in the onResume of my activity? Why? Is the mTicker Runnable stopped?

MyActivity.java

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    mHandler = new Handler();

    mTicker = new Runnable() {
        public void run() {
            if(mClockStopped) return;
            long now = System.currentTimeMillis();
            mCalendar.setTimeInMillis(now);  
            mClock.setText(DateFormat.format("kk:mm", mCalendar));
            mClock.invalidate();
            long upTime = SystemClock.uptimeMillis();
            long next = upTime + (60000 - now % 60000);
            mHandler.postAtTime(mTicker, next);
        }
    };
    mTicker.run();

    /* more stuff */

}

@Override
    public void onResume()
    {
        super.onResume();
        mClockStopped = false; 
    }

    @Override
    public void onPause()
    {
        mClockStopped = true;        
        super.onPause();
    }

Solution

  • Maybe is not that simple, but setting mClockStopped to true make your runnable's run() exit.

    You should call

    mClockStopped = false; 
    mTicker.run();
    

    In onResume