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:
- 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. - Run a background service: Not too familiar with this area.
What is the best approach here? Do you have a better technique in mind?