Display alert dialog after specific time

89 Views Asked by At

I want to start a timer (i think in this case CountDownTimer) as soon as I get a specific wakelock. Once the countdown timer finishes, i want to display an alert dialog. When the wakelock is released, the timer should be killed. When the timer is running and I get a user activity, I want to kill the previous timer and start a new one (or maybe reset this one)

What would be the best way for me to implement this?

1

There are 1 best solutions below

0
Deiivid On
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()
            }
    `