On screen timer in Android application?

与世无争的帅哥 提交于 2019-12-13 18:17:10

问题


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:


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



来源:https://stackoverflow.com/questions/8248298/on-screen-timer-in-android-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!