在后台运行CountDownTimer

时间:2018-06-08 18:57:55

标签: android countdowntimer

我正在制作倒数计时器,我想在后台运行它。

我运行下面的代码,但问题是,当我返回活动时,计时器不会再次运行,它会在我离开活动时停止。

如何解决此问题?

我申请了this code

这是代码:

public class HarvestingActivity extends AppCompatActivity {


private CountDownTimer countDownTimer;
private boolean mTimerRunning;
private static final long START_TIME_IN_MILLIS = 60000;

private long mTimeLeftInMillis;
private TextView mTextViewCountDown;
private long mEndTime;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_harvesting);

    FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
    assert currentUser != null;
    mTextViewCountDown = findViewById(R.id.text_timer);
    startTimer();
}

private void startTimer() {
    mEndTime = System.currentTimeMillis() + mTimeLeftInMillis;

    countDownTimer = new CountDownTimer(START_TIME_IN_MILLIS, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            mTimeLeftInMillis = millisUntilFinished;
            updateTime();
        }

        @Override
        public void onFinish() {
            mTimerRunning = false;
        }
    }.start();
    mTimerRunning = true;
}

private void updateTime() {
    int minutes = (int) (mTimeLeftInMillis / 1000);
    mTextViewCountDown.setText(String.valueOf(minutes));
}

@Override
protected void onStop() {
    super.onStop();

    SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();

    editor.putLong("millisLeft", mTimeLeftInMillis);
    editor.putBoolean("timerRunning", mTimerRunning);
    editor.putLong("endTime", mEndTime);
    editor.apply();

    if (countDownTimer != null) {
        countDownTimer.cancel();
    }
}

@Override
protected void onStart() {
    super.onStart();

    SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
    mTimeLeftInMillis = prefs.getLong("millisLeft", START_TIME_IN_MILLIS);
    mTimerRunning = prefs.getBoolean("timerRunning", false);

    updateTime();

    if (mTimerRunning) {
        mEndTime = prefs.getLong("endTime", 0);
        mTimeLeftInMillis = mEndTime - System.currentTimeMillis();

        if (mTimeLeftInMillis < 0) {
            mTimeLeftInMillis = 0;
            mTimerRunning = false;
            updateTime();
            //updateButtons();
        } else {
            startTimer();
        }
    }
}

@Override
protected void onRestart() {
    super.onRestart();
}
   }

0 个答案:

没有答案