1

I want to cancel the timer when user presses the back button or minimizes the app. I have tried using cancel() on 'override fun onDestroy()' but still the timer is running.

Below is my countdown timer code

countDownTimer = object : CountDownTimer(Constants.timerDuration, 1000) {
        override fun onTick(millisecondFinished: Long) {
            binding?.tvTimer?.text = (millisecondFinished / 1000).toString()

            Log.i("millis", "onTick: $millisecondFinished")
        }

        override fun onFinish() {
            val action = GameplayDirections.actionGameplayToGameover()

            findNavController().navigate(action)

        }
    }.start()`

This is how I have initialized the countdown variable

private var countDownTimer: CountDownTimer? = null

And below is the code for cancelling the timer

override fun onDestroy() {
    super.onDestroy()
    countDownTimer.cancel()
    countDownTimer = null
    Log.i("destroy", "onDestroyView: destroyed")
    binding = null
}

I have referred to many links, still I wasn't able to resolve this issue. I can see the timer running in the logcat even when I press the back button or minimize the app.

I have implemented countdown timer in fragment and after the timer is finished I am traversing to other fragment. And because the timer is not cancelling I am getting an error as shown below.

2022-07-24 12:25:15.643 32685-32685/io.ronli.protypist E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.ronli.protypist, PID: 32685
java.lang.IllegalStateException: Fragment Gameplay{735bc2f} (915d1b65-13a2-40f3-b94a-4519fde2252d) not associated with a fragment manager.
    at androidx.fragment.app.Fragment.getParentFragmentManager(Fragment.java:1059)
    at androidx.navigation.fragment.NavHostFragment$Companion.findNavController(NavHostFragment.kt:375)
    at androidx.navigation.fragment.FragmentKt.findNavController(Fragment.kt:29)
    at io.ronli.protypist.ui.Gameplay$startTimer$1.onFinish(Gameplay.kt:325)
    at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:142)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:210)
    at android.os.Looper.loop(Looper.java:299)
    at android.app.ActivityThread.main(ActivityThread.java:8105)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1045)

1 Answers1

2

If you want to stop the timer when user press the back button or minimize the app you should call cancel method in onPause like this:

override fun onPause() {
        super.onPause()
        countDownTimer.cancel()
}

And the error is not related to the timer. It's about navigation. You can see similar situation in below :

Fragment XXX {} not associated with a fragment manager

Alireza Barakati
  • 1,016
  • 2
  • 9
  • 23