My Countdown Timer Stuck when phone screen is locked

Viewed 178

I have developed a workout app. I've two timers on the screen one is for the total timer and one for exercise time also some tts and MediaPlayer sounds. When the screen is locked my exercise timer is stuck after 10 seconds but my total remaining time timer is still running. So confused about why is it happening, I've verified battery optimization permission on\off but the issue is still the same. I've set a toast in tick function and I turn off the screen when I come back toast is showing but my timer is stuck. Can anyone help to get out of this? Thanks in advance. Countdown works fines when the screen is opened or connected to the charger.

Exercise Timer code below...

excerciseCountDownTimer = new CountDownTimer(seconds * 1000, 1000) {

            public void onTick(long millisUntilFinished) {

                totalExcerciseSec = (int) (millisUntilFinished / 1000);

                int currentMinute = totalExcerciseSec / 60;

                int currentSecond = totalExcerciseSec % 60;

                binding.workoutTimeTv.setText(String.format("%02d", currentMinute) + ":" + String.format("%02d", currentSecond));


                if (totalExcerciseSec == 0) {

                    totalRemaingCountDownTimer.cancel();
                    onExerciseCompleteActions();

                }

            }

            public void onFinish() {
            }
        }.start();

Total Remaining Timer code below...

totalRemaingCountDownTimer = new CountDownTimer(seconds * 1000, 1000) {

            public void onTick(long millisUntilFinished) {

                totalRemainingSecs = (int) (millisUntilFinished / 1000);

                int minutes = totalRemainingSecs / 60;

                int second = totalRemainingSecs % 60;

                timerPlaying = true;

                binding.totalRemainingTimeTv.setText(String.format("%02d", minutes) + ":" + String.format("%02d", second));
            }

            public void onFinish() {
            }
        }.start();
2 Answers

Your activity is getting stopped or destroyed and that's why your timer gets stuck. To keep the timer running even if the app is closed or killed, see this way:-

You can use this technique to detect how long the user was inactive (even when the app is in the background).

  1. Create a SharedPreference & its Editor object. Then declare 3 long variables such:
mMillisUntilFinished = pref.getLong("millisUntilFinished",60*1000); // Replace with your time
long userExitedMillis = pref.getLong("userExitedMillis",0);
long timeLeft = mMillisUntilFinished - (System.currentTimeMillis() - userExitedMillis);
  1. Pass timeLeft as millisInFuture. Inside timer, assign millisUntilFinished to a public variable in every tick
new CountDownTimer(timeLeft,1000){
            @Override
            public void onTick(long millisUntilFinished) {
                Log.d("TAG", "Time left : " + millisUntilFinished/1000 + " sec");
                mMillisUntilFinished = millisUntilFinished;
            }

            @Override
            public void onFinish() {
                // Timer completed
            }
        }.start();

  1. Save this mMillisUntilFinished variable & current time in shared preference at onStop().
@Override
    protected void onStop() {
        super.onStop();
        editor.putLong("millisUntilFinished",mMillisUntilFinished);
        editor.putLong("userExitedMillis",System.currentTimeMillis());
        editor.apply();
    }

Tip : If you subtract userExitedMillis from System.currentTimeMillis() then you will get the activity inactive time (in mili second).

Related