我正在設計適用於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