Search code examples
androidkotlinandroid-handlerandroid-looper

Create a function that runs every interval and stop that function from running with Kotlin in Android Studio


I want to create a function that runs every 50ms (the equivalent of setInterval in JS). So far, this is what I have:

val mainHandler = Handler(Looper.getMainLooper())
mainHandler.post(object: Runnable {
    override fun run() {
        progressBar.progress += 1
        mainHandler.postDelayed(this, 50)
    }
})

It works, but how do I stop the run() function from running any further when the progress has reached 100? Also, is there a way to cancel the run and reset progress to 0 when I click a button (like clearInterval in JS)? For reference, I want this:

buttonView.setOnClickListener {
    stopRunFromRunning()
    resetProgressTo0()
}

progress.onReach100 {
    stopRunFromRunning()
}

Solution

  • assign the runnable into a variable and you can remove from handler's callback

    val progressBar = findViewById(R.id.progress_bar)
    val btn = findViewById(R.id.btn)
    
    val handler = Handler(Looper.getMainLooper())
    val runnable = Runnable {
        override public fun run() {
         progressBar.progress+=1
           if(progressBar.progress<100)
              handler.postDelayed(this, 50) 
        }
    }
    
    handler.post(runnable, milliseconds)
    
    btn.setOnClickListener {
        handler.removeCallbacks(runnable)
        progressBar.progress=0
    }