Android:CountDownTimer 跳过最后一个 onTick()!

新手上路,请多包涵

代码:

 public class SMH extends Activity {

    public void onCreate(Bundle b) {
        super.onCreate(b);
        setContentView(R.layout.main);

        TextView tv = (TextView) findViewById(R.id.tv);

        new CountDownTimer(10000, 2000) {
            public void onTick(long m) {
               long sec = m/1000+1;
               tv.append(sec+" seconds remain\n");
            }
            public void onFinish() {
               tv.append("Done!");
            }
        }.start();
   }

输出:

还剩 10 秒

还剩 8 秒

还剩 6 秒

还剩 4 秒

完毕!

问题:

我如何让它显示“ _还剩 2 秒_”?经过的时间确实是 10 秒,但最后一次 onTick() 永远不会发生。如果我将第二个参数从 2000 更改为 1000,则输出如下:

还剩 10 秒

还剩 9 秒

还剩 8 秒

还剩 7 秒

还剩 6 秒

还剩 5 秒

还剩 4 秒

还剩 3 秒

还剩 2 秒

完毕!

所以你看,它似乎跳过了最后一个 onTick() 调用。顺便说一句,XML 文件基本上是默认的 main.xml,其中 TextView 分配了 id tv 并且文本设置为“”。

原文由 ProgrammingMakesMeQQ 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

我不知道为什么最后一个滴答声不起作用,但您可以使用 Runable 创建自己的计时器,例如。

 class MyCountDownTimer {
    private long millisInFuture;
    private long countDownInterval;
    public MyCountDownTimer(long pMillisInFuture, long pCountDownInterval) {
            this.millisInFuture = pMillisInFuture;
            this.countDownInterval = pCountDownInterval;
        }
    public void Start()
    {
        final Handler handler = new Handler();
        Log.v("status", "starting");
        final Runnable counter = new Runnable(){

            public void run(){
                if(millisInFuture <= 0) {
                    Log.v("status", "done");
                } else {
                    long sec = millisInFuture/1000;
                    Log.v("status", Long.toString(sec) + " seconds remain");
                    millisInFuture -= countDownInterval;
                    handler.postDelayed(this, countDownInterval);
                }
            }
        };

        handler.postDelayed(counter, countDownInterval);
    }
}

并开始它,

 new MyCountDownTimer(10000, 2000).Start();


编辑高飞的问题

你应该有一个变量来保存计数器状态(布尔值)。然后你可以像 Start() 一样写一个 Stop() 方法。

GOOFY 问题的 EDIT-2

实际上停止计数器没有错误,但在停止(恢复)后再次启动时有错误。

我正在编写一个新的更新的完整代码,我刚刚尝试过并且它正在运行。这是一个基本的计数器,在屏幕上显示时间,带有开始和停止按钮。

计数器类

public class MyCountDownTimer {
    private long millisInFuture;
    private long countDownInterval;
    private boolean status;
    public MyCountDownTimer(long pMillisInFuture, long pCountDownInterval) {
            this.millisInFuture = pMillisInFuture;
            this.countDownInterval = pCountDownInterval;
            status = false;
            Initialize();
    }

    public void Stop() {
        status = false;
    }

    public long getCurrentTime() {
        return millisInFuture;
    }

    public void Start() {
        status = true;
    }
    public void Initialize()
    {
        final Handler handler = new Handler();
        Log.v("status", "starting");
        final Runnable counter = new Runnable(){

            public void run(){
                long sec = millisInFuture/1000;
                if(status) {
                    if(millisInFuture <= 0) {
                        Log.v("status", "done");
                    } else {
                        Log.v("status", Long.toString(sec) + " seconds remain");
                        millisInFuture -= countDownInterval;
                        handler.postDelayed(this, countDownInterval);
                    }
                } else {
                    Log.v("status", Long.toString(sec) + " seconds remain and timer has stopped!");
                    handler.postDelayed(this, countDownInterval);
                }
            }
        };

        handler.postDelayed(counter, countDownInterval);
    }
}

活动课

public class CounterActivity extends Activity {
    /** Called when the activity is first created. */
    TextView timeText;
    Button startBut;
    Button stopBut;
    MyCountDownTimer mycounter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        timeText = (TextView) findViewById(R.id.time);
        startBut = (Button) findViewById(R.id.start);
        stopBut = (Button) findViewById(R.id.stop);
        mycounter = new MyCountDownTimer(20000, 1000);
        RefreshTimer();
    }

    public void StartTimer(View v) {
        Log.v("startbutton", "saymaya basladi");
        mycounter.Start();
    }

    public void StopTimer(View v) {
        Log.v("stopbutton", "durdu");
        mycounter.Stop();
    }

    public void RefreshTimer()
    {
        final Handler handler = new Handler();
        final Runnable counter = new Runnable(){

            public void run(){
                timeText.setText(Long.toString(mycounter.getCurrentTime()));
                handler.postDelayed(this, 100);
            }
        };

        handler.postDelayed(counter, 100);
    }
}

主.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">
    <TextView android:textAppearance="?android:attr/textAppearanceLarge"
              android:text="TextView" android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:id="@+id/time">
    </TextView>
    <Button android:text="Start"
            android:id="@+id/start"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="StartTimer">
    </Button>
    <Button android:text="Stop"
            android:id="@+id/stop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="StopTimer">
    </Button>
</LinearLayout>

原文由 Okan Kocyigit 发布,翻译遵循 CC BY-SA 3.0 许可协议

我检查了 CountDownTimer 的源代码。 “missing tick”来自 CountDownTimer 的一个特殊功能,我还没有在其他地方看到它的记录:

在每次报价开始时,在调用 onTick() 之前,计算倒计时结束前的剩余时间。如果这个时间小于倒计时时间间隔,则 不再 调用onTick。相反,只会安排下一个滴答声(将调用 onFinish() 方法的地方)。

鉴于硬件时钟并不总是非常精确,后台可能有其他进程延迟运行 CountDownTimer 的线程,加上 Android 本身在调用 CountDownTimer 的消息处理程序时可能会产生一个小的延迟,这很可能是在倒计时结束前调用最后一个报价将至少延迟一毫秒,因此不会调用 onTick()。

对于我的应用程序,我只是通过使滴答间隔“稍微”变小(500 毫秒)来解决这个问题

    myCountDownTimer = new CountDownTimer(countDownTime, intervalTime - 500) {
                                   ...
    }

我可以保留我的代码原样。对于间隔时间长度至关重要的应用程序,此处发布的其他解决方案可能是最好的。

原文由 Nantoka 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题