Search code examples
javaandroidtimerrunnablestopwatch

Is there already a StopWatch class for android and why doesn't my implementation work?


Lately I saw http://developer.android.com/reference/android/os/CountDownTimer.html and wondered if there is an respective class for stop watches since I want to tell the user of my App how long he's already trying to solve the puzzle. I mean it isn't that complicated to program such a stop watch on your own. I tried something like

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
                long seconds = (System.currentTimeMillis() - t) / 1000;
                statusBar.setText(String.format("%02d:%02d", seconds / 60, seconds % 60));
            }
        }

    };
    statusBar.post(runnable);

But bizarrely the layout of my activity isn't inflated anymore since I have this statusBar.post(runnable); in the end of the acitivity's onCreate method meaning that after starting the app I only see a white screen instead of the normal gui.


Solution

  • You should use a Chronometer.

    But anyway, your code can work if you remove the sleep from UI thread.

    private final Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if (mStarted) {
                long seconds = (System.currentTimeMillis() - t) / 1000;
                statusBar.setText(String.format("%02d:%02d", seconds / 60, seconds % 60));
                handler.postDelayed(runnable, 1000L);
            }
        }
    
    };
    
    private Hanlder mHandler;
    private boolean mStarted;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Handler();
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        mStarted = true;
        mHandler.postDealyed(runnable, 1000L);
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        mStarted = false;
        mHandler.removeCallbacks(mRunnable);
    }