I'm trying to add a red flash to my application when some event occurs. Using the windowManager, i've created and added a simple view that just fills the canvas with red, and initializes the opacity to 0%
To implement the "flash", I plan to set the opacity to 100%, sleep for 25ms, then set the opacity back to 0%
I know that I can get this to work properly by doing something like
view.alpha = 255f
handler.postDelayed(
Runnable {
view.alpha = 0f
}, 25)
However, I am confused about this behavior when I try to add a delay using Thread.sleep()
directly on the main thread
view.alpha = 255f
Thread.sleep(25)
view.alpha = 0f
This basically makes it so that the first statement view.alpha = 255f
is never executed.
However, if i were to put this code in a background thread, then the behavior works as I expect
Thread(
Runnable {
view.alpha = 255f
Thread.sleep(50)
visualizer.alpha = 0f
})
.start()
My questions
- Why do view changes before sleeping main thread not get executed (or at least are not visible)?
- Why am I able to change the opacity of a view on a background thread? Is this not considered a view change and needs to be done from the UI thread?