Richard
Richard

Reputation: 7433

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()
}

Upvotes: 2

Views: 1466

Answers (2)

Master Zzzing
Master Zzzing

Reputation: 563

when working with progressbar, I do something like:

var stop = false
val runnable = Runnable {
       while (progressBar.progress < 100) {
            if(stop) break

            progressBar.progress += 1
            // Try to sleep the thread for 50 milliseconds
            try {
                Thread.sleep(50)
            } catch (e: InterruptedException) {
                e.printStackTrace()
            }
       }
}
Thread(runnable).start()

// stop
stopButtonClick -> {
    stop = true
    progressBar.progress = 0
}

now you can tell your counter to stop before progressBar.progress = 100 and your counter also knows when to stop itself. Hope it helps

Upvotes: 0

Sujan Poudel
Sujan Poudel

Reputation: 853

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
}

Upvotes: 3

Related Questions