Keep button disabled for specified interval in android, even when app is restarted

点点圈 提交于 2021-02-10 14:23:05

问题


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?


回答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.



来源:https://stackoverflow.com/questions/64280509/keep-button-disabled-for-specified-interval-in-android-even-when-app-is-restart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!