Having A Timer Use The Main Thread In Kotlin
Solution 1:
You can use an Handler which when declared from the Main Thread(eg. in the Activity) will be attached to it,
You could try this :
valdelayedHandler= Handler()
delayedHandler.postDelayed({
//// Your Code
}, 2000)
Or you can also keep your Timer, simply declare a Handler outside the timer, and use the Handler post() Method from your Timer
Solution 2:
You can extend timerTask to return on the main thread. Basically, get a Hander that runs on the main thread:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
publicvoidrun() {
// UI code goes here
}
});
Then have timerTask execute its function parameter in the run method above. Alternatively, you can just have that code in you lambda or even use activity.runOnUiThread()
. Really the correct solution comes down to how often you do this in your code, of it's a one off just use runOnUiThread
.
Solution 3:
Although the previous answers are working, they are not very kotlin
Way nicer is something like this
Handler(mainLooper).post { someTextView.text = "Hello world!" }
Post a Comment for "Having A Timer Use The Main Thread In Kotlin"