【问题标题】:Display alert dialog after specific time在特定时间后显示警报对话框
【发布时间】:2022-11-07 16:04:46
【问题描述】:
一旦我得到一个特定的唤醒锁,我想启动一个计时器(我认为在这种情况下是 CountDownTimer)。倒数计时器完成后,我想显示一个警报对话框。当唤醒锁被释放时,定时器应该被杀死。当计时器正在运行并且我得到用户活动时,我想终止前一个计时器并启动一个新计时器(或者可能重置这个计时器)
什么是我实现这一点的最佳方式?
【问题讨论】:
标签:
android
android-alertdialog
countdowntimer
wakelock
【解决方案1】:
Yes you can do it, the only thing you need to do is like this -->
`val dialogListener = DialogInterface.OnClickListener { dialog, which ->
when (which) {
BUTTON_POSITIVE -> {
}
DialogInterface.BUTTON_NEGATIVE -> {
}
}
}
val dialog = AlertDialog.Builder(this)
.setTitle(“YOUR TITLE HERE”)
.setMessage(“YOUR MESSAGE HERE)
.setPositiveButton(“TEXT OF BUTTON”)
.setNegativeButton(“TEXT OF BUTTON”)
.create()
dialog.setOnShowListener(object : OnShowListener {
private val AUTO_DISMISS_MILLIS = 5000 //Timer in this case 5 Seconds
override fun onShow(dialog: DialogInterface) {
//if you want to have stuff done by your buttons it's going go be here with a respective call like (dialog as AlertDialog).getButton(The button you want positive or negative)
then everything you want to happen on it
*************************************************
//here is the timer associated to the button
val defaultButton: Button =
dialog.getButton(AlertDialog.BUTTON_POSITIVE)
val positiveButtonText: CharSequence = defaultButton.text
object : CountDownTimer(AUTO_DISMISS_MILLIS.toLong(), 100) {
override fun onTick(millisUntilFinished: Long) {
defaultButton.text = java.lang.String.format(
Locale.getDefault(), "%s (%d)",
positiveButtonText,
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) + 1
)
}
override fun onFinish() {
//everything you wanna do on the moment the timer is off is going to happen here if you wanna open another dialog you need to call it here
}
}.start()
}
})
dialog.show()
}
`