gpt4 book ai didi

android - 即使在重新启动应用程序的情况下,也可以在android中按指定的间隔禁用按钮

转载 作者:行者123 更新时间:2023-12-02 13:25:38 26 4
gpt4 key购买 nike

我想在两次按下按钮之间以分钟为单位添加固定间隔。我尝试使用postDelayed()CountDownTimer,但是如果重新启动应用程序,则可以再次按下按钮。
使用postDelayed()

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

使用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()
}
就我的用例而言,即使关闭应用程序,按钮也应在指定的时间间隔内保持禁用状态。我想到了两种方法:
  • 计算再次单击该按钮时的时间戳,并启动postDelayed()计时器。还要将时间戳记保存在共享首选项中。如果应用重新启动,则获取保存的值并启动计时器。
  • 运行后台服务:对该区域不太熟悉。

  • 最好的方法是什么?您是否有更好的技巧?

    最佳答案

    我认为您可以在共享首选项中保存一个时间戳(也许很简单,例如使用System.currentTimeMillis()获得的值),然后,当您的应用程序启动时,您将启动一个计时器,将超时设置为当前时间与保存的时间之间的差在共享的首选项中(基本上是您的第一个建议)。
    每次按下启用的按钮时,也会在共享的首选项中放置一个新值。
    对我来说,后台服务选项似乎有些过大。
    如果不需要直观地更改按钮,则可以避免完全使用计时器,而只需在按下按钮时才根据共享首选项中的值进行评估。

    关于android - 即使在重新启动应用程序的情况下,也可以在android中按指定的间隔禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64280509/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com