java - 计时器记录问题?

标签 java android timer

我正在制作一个带有计时器的应用程序。我想在 10 秒结束时将日志放入 logcat 中。计时器在 20 秒时执行不同的任务。这是我的尝试:

enter image description here

这是代码:

public class TwentySeconds extends Service {

MediaPlayer mp;

final String TAG = "MyCountdown";

CountDownTimer cdt;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Log.v(TAG, "In start command");

     cdt = new CountDownTimer(20000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            long timeRemaining = 20000 - millisUntilFinished;
            if(timeRemaining % 1000 == 0){
                Log.v(TAG, "Time remaining" +(timeRemaining % 1000) + " seconds left");
            }
        }
        @Override
        public void onFinish() {
            Log.v(TAG, "Finished");

            Intent intent = new    Intent(TwentySeconds.this,GameOver.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Log.v(TAG, "About to start activity");
            startActivity(intent);
        }
    };
    cdt.start();
    return START_STICKY;
}
@Override
public void onDestroy() {
    super.onDestroy();
}
}

代码的逻辑看起来很好,但由于某种原因,它没有显示。非常感谢您抽出宝贵的时间,请告诉我。

{Rich}

最佳答案

CountDownTimer 不是 100% 精确的计时器,因此您不应尝试进行如此精确的计算,因为 99% 的情况下它都会失败。

也许只是这样做:

millisUntilFinished / 1000

因为您的间隔是 1 秒。

试试这个:

 @Override
    public void onTick(long millisUntilFinished) {
          long timeRemaining = 20000 - millisUntilFinished;
          Log.v(TAG, "Time remaining " + (timeRemaining / 1000) + " seconds left");
    }

关于java - 计时器记录问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33512379/

相关文章:

java - Radix 在 Java 中使用队列对字符串数组进行排序

Android USB 大容量存储

java - android studio AsyncTask 无意且 context.finish 崩溃

c - 如何一次又一次地生成相同的信号(SIGALRM)?

android - 如何在第二个 Activity 中没有任何操作时返回到主要 Activity

Java 对列表中的所有对象执行方法

java - Play Framework 在使用空值的 Web 服务调用期间从 URL 中剥离 "="(导致结束点出现 500 错误)

java - 画廊中如何将图片从一个文件夹移动到另一个文件夹

android - 如何在运行时将图像从 Android 设备的图库映射到 Unity 应用程序中的纹理?

c# - C# 中使用 System.Threading.Timer 的延迟队列