On screen timer in Android application?

2019-08-09 16:39发布

My friends and I who are trying to create a game want to use a timer as a way of scoring players, and so we want to display an on-screen timer starting at 0 at the start of the game and stopping when they finish the game.

I have looked at some other posts as well as on the android dev website into using a Handler and a Runnable object in order to make it work as I want, but as of right now the run() method inside of the Runnable object is being completely skipped over, so nothing is being done. Right now, I have the following inside of our Activity's onCreate method:

    mHandler = new Handler();
    mStartTime = System.currentTimeMillis();
    mHandler.removeCallbacks(mUpdateTimeTask);
    mHandler.postDelayed(mUpdateTimeTask, 100);

    mUpdateTimeTask = new Runnable()
    {
        public void run() 
        {
            final long start = mStartTime;
            long millis = SystemClock.uptimeMillis() - start;
            int seconds = (int) (millis / 1000);
            seconds = seconds % 60;

            mHandler.postAtTime(this,
                    (start + seconds + 1) * 1000);

            elapsed.setText(seconds);
        }
     };

Now first off, can anyone tell me why the run() method is being completely skipped? And also, will this work for what we are trying to do? Or should we have the Runnable object somewhere else? Use a different approach? This is our first time working with a timer, so any help is appreciated!

1条回答
Summer. ? 凉城
2楼-- · 2019-08-09 17:22

Perhaps you need to call mHandler.postDelayed(mUpdateTimeTask, 100) after the mUpdateTimeTask = new Runnable() assignment

查看更多
登录 后发表回答