Search code examples
androidkotlinmotionevent

How to set timer on click?


Want to set timer on 1 minute, and if there were no clicks, then call my method viewContract.lockScreen()

Here is my code:

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    viewContract.lockScreen()
    return super.dispatchTouchEvent(ev)
}

Solution

  • I would do a postDelayed(...) on a Handler like:

    val handler = Handler(Looper.getMainLooper())
    val timerDuration = TimeUnit.MINUTES.toMillis(1)
    val timerAction = Runnable { /* call your method here... */ }
    
    fun startTimer() =  handler.postDelayed(timerAction, timerDuration)
    fun cancelTimer() = handler.removeCallbacks(timerAction)
    

    EDIT:

    It's a bit unclear in the question since you state that you want to execute viewContract.lockScreen() once the 1 minute has passed without interaction, but then you call the same method in dispatchTouchEvent which is when a touch occur. But as I see it, this would be how you should call it:

    val handler = Handler(Looper.getMainLooper())
    val timerDuration = TimeUnit.MINUTES.toMillis(1)
    val timerAction = Runnable { viewContract.lockScreen() }
    
    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        cancelTimer()
        return super.dispatchTouchEvent(ev)
    }
    
    fun startTimer() =  handler.postDelayed(timerAction, timerDuration)
    fun cancelTimer() = handler.removeCallbacks(timerAction)
    

    Also it's not really clear when the timer should start, but in any case, just call startTimer() when that should be happening.