我正在制作一个带有计时器的应用程序。我想在 10 秒结束时将日志放入 logcat 中。计时器在 20 秒时执行不同的任务。这是我的尝试:
这是代码:
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/