我正在设计适用于Android 2.2的计时器/倒数计时器应用程序,并希望单击一次按钮即可同时启动计时器和。所以,理想情况下,我想在秒(时间)天文钟和计时器在同一个实例改变。 (即使计时器正在计数,计时器也会倒计时)。由于我使用的是由Android提供的天文台和定时器功能,我写了下面的代码,当用户按下“开始”按钮同时在Android中启动两个(或更多)功能
private boolean mStartPressedOnce = false;
long mTimeWhenStopped = 0;
Chronometer mChronometer;
MyCounter mCounter;
...
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.StartButton:
// Perform some initialization for the chronometer depending
// on the button press
if (mStartPressedOnce == false) {
mChronometer.setBase(SystemClock.elapsedRealtime());
} else {
mChronometer.setBase(SystemClock.elapsedRealtime() + mTimeWhenStopped);
}
// Perform the initialization for the timer
mCounter = new MyCount(45000, 1000);
// Fire up the chronometer
mChronometer.start();
// Fire up the timer
mCounter.start();
break;
case R.id.ResetButton:
// Reset the chronometer
mChronometer.setBase(SystemClock.elapsedRealtime());
mTimeWhenStopped = 0;
break;
case case R.id.StopButton:
mStartPressedOnce = true;
// Stop the chronometer
mTimeWhenStopped = mChronometer.getBase() - SystemClock.elapsedRealtime();
mChronometer.stop();
break;
}
...
public class MyCounter extends CountDownTimer {
@Override
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
// Nothing to do here
}
@Override
public void onTick(long millisUntilFinished) {
long seconds = (long) (millisUntilFinished/1000);
long minutes = (long) ((millisUntilFinished/1000)/60);
long hours = (long) (((millisUntilFinished/1000)/60)/60);
// Do some formatting to make seconds, minutes and hours look pretty
// Update the timer TextView
(TextView) findViewById(R.id.CountDownTimerTextView))
.setText(hours + ":" + minutes + ":" + seconds);
}
}
虽然它看起来记时计和计时器秒数等在同步最初为,经过短时间后,它们似乎熄灭,并且第二次更新都发生在不同的时间。
想知道我能做些什么来解决这个问题。我没碰到过 - 读这个线程
Running multiple AsyncTasks at the same time -- not possible?
我认识到,有可能是设计变更需要的,但我不知道需要做什么。
编辑:包括类型天文台和定时器和方法使用天文台计算的时间 - 每jolivier和njzk2的建议
什么是你的mChronometer和mCounter,你如何测量时间? – njzk2
为什么使用小部件而不是System.nanoTime()或currentTimeMillis()? – Shark
@Shark,不知道我知道你的问题的答案。谢谢。 – aLearner