Android- how do I know what methods should run on the main thread?

29 Views Asked by At

I know there is an annotation @MainThread sometimes, but not in all cases.

For example, in the view class, how do I know if a method can or cannot and should or should not be called from the main thread or I can call it from a computational thread?

1

There are 1 best solutions below

0
Iván Garza Bermea On

Everything on that has to do with the app's UI should be run in the main thread, otherwise you'll very likely get an Exception.

To answer your question more specifically, you probably want to make sure you call anything inside a view directly from the main thread. But again, when in doubt, try it out, and you'll get an exception if you're doing anything wrong.

A few way to move functionality into the main thread is using the Looper. getMainLooper(), or using Kotlin coroutines with the Dispatchers.Main dispatcher.