1

I want to add a fixed interval in minutes between 2 button presses. I tried using postDelayed() and CountDownTimer but I'm able to press the button again if I restart the app.

Using postDelayed()

        binding.trialButton.setOnClickListener {
            Timber.d("Delay button pressed")
            binding.trialButton.isEnabled = false
            binding.trialButton.postDelayed( {
                binding.trialButton.isEnabled = true
            }, 40*1000);
        }

Using CountDownTimer

        binding.trialButton.setOnClickListener {
            Timber.d("Delay button pressed")
            binding.trialButton.isEnabled = false

            val timer = object: CountDownTimer(30000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    Timber.d("Tick")
                }

                override fun onFinish() {
                    binding.trialButton.isEnabled = true
                }
            }
            timer.start()
        }

For my use case, the button should remain disabled for the specified interval, even when the app is closed. I have two approaches in mind:

  1. Calculate the timestamp when the button will be clickable again and start a postDelayed() timer. Also save the timestamp in shared preferences. If the app is restarted, fetch the saved value and start a timer.
  2. Run a background service: Not too familiar with this area.

What is the best approach here? Do you have a better technique in mind?

secretshardul
  • 1,635
  • 19
  • 31

1 Answers1

1

I think you could save a timestamp (maybe something simple, like the value obtained with System.currentTimeMillis()) in the shared preferences, then, when your application starts, you start a timer with a timeout set to the difference between the current time and the one saved in the shared preferences (basically your first proposal).
Everytime you press the enabled button, you also put a new value in the shared preferences.

The background service option seems a little overkill to me.

If you don't need to visually change the button, you could avoid using the timer entirely, only evalutating against the value in the shared preferences when the button is pressed.

gscaparrotti
  • 663
  • 5
  • 21
  • Seems logical.But for my use case Your second approach is also pretty good, but for my use case I need to grey out the button when it's not clickable. – secretshardul Oct 09 '20 at 13:29