Is the same thread that's used for all activities throughout a single application?
Threading in Android is simpler then you might think, any application, in general, can have n
number of threads, but there is only one UI Thread. The thread on which all UI related changes are made is what is called the UI thread. With RunOnUIThread
If the current thread is UI thread, that code will be executed immediately, otherwise (if the current thread is not the UI thread), the code will be queued in UI thread's event queue. In case if you make any changes in your UI and if it is in some background thread like an async-await
based Restful Api
call then it won't get reflected as that was not made on the Background thread and hence id not known to the running 'Activity', since RunOnUIThread
is only available in an activity context in fragments you will need to use the Activity property to get it and use it.
If so , do I must use Activity.RunOnUIThread? Or Is there any alternative?
It is not always needed, but there are scenarios where you might wanna use it. (As explained above)
For eg: An async method that opens a popup after its done executing will need the RunOnUIThread
method otherwise your Pop-Up or alert will never show up because the change was not made on UIThread but an asynchronous background thread.
Similarly, If you have an OnCreate
method and you have a requirement to show an Alert as soon as the page opens now if you decide to write this down directly in the OnCreate
method there are chances it might not show in that case you run it on UIThread.()