Should new Handler(Looper.getMainLooper()) instance be created on every UI call?

Viewed 25

I currently keep a single Handler instance (spanning through multiple activities) and use it for each update UI call:

class CrossActivityUiUpdatingClass {
    private val handler = Handler(Looper.getMainLooper())
    fun updateUi(action: () -> Unit) {
        handler.post(action)
    }
}

Everything works fine, but I'm not sure about this: if the main/UI thread is subject to change by Android OS while switching activities, then my code should not be correct.

If it's true that Android OS may declare another thread to be the Main/UI thread, then creating a new Handler instance on each UI update would be safer, but at the same time it seems like a waste of resources:

class CrossActivityUiUpdatingClass {
    fun updateUi(action: () -> Unit) {
        private val handler = Handler(Looper.getMainLooper())
        handler.post(action)
    }
}

How to approach this problem to make it correct and effective at the same time? What's the lifecycle of Handler?

0 Answers
Related