Search code examples
javakotlinrunnableandroid-handlerandroid-looper

Handler postDelay() from background thread


Can anyone see any reason why this would not be working?

 override fun resetAnimations() {
    Log.d("MainActivity", "start")
    Handler().postDelayed( { reset()}, 1500)
    Log.d("MainActivity", "end")
 }

 fun reset(){
     Log.d("MainActivity", "reset")
  }

I'm calling this in some arbitrary place in my activity but the reset() method is never called. In the logs I'm only getting the following

D/MainActivity: start

It looks like its blocking on postDelay.. even when I set the value to 1 or replace postDelay with pose, doesn't work.

Update:

when i implement like this, it works;

 private lateinit var handler : Handler

 override fun onCreate(savedInstanceState: Bundle?) {
    handler = Handler()
    resetAnimations()
 }

 override fun resetAnimations() {
    handler.postDelayed( { reset()}, 1500)
 }

I think the problem has something to do with the fact that I was calling resetAnimations() from a background thread, and creating the handler on the background thread..


Solution

  • I was calling resetAnimations() from a background thread.

    That's the problem. Your handler couldn't post a Message onto a MessageQueue, because there isn't any MessageQueue on your background thread.

    So, instead of this:

    Handler().postDelayed( { reset()}, 1500)
    

    Perform this:

    Handler(Looper.getMainThread()).postDelayed( { reset()}, 1500)