Very good, I have a question related to when I have to use (or why) Activity.runOnUiThread() instead of, or vice versa of Handler.post(Runnable) to update, for example, a TextView or ProgressBar , or failing that, I must to use Asyntask .
I have been looking for information in the following links, but I still don't have a clear answer. What is the best option depending on each case?
Android: What's the difference between Activity.runOnUiThread and View.post?
runOnUiThread vs Handler.post(runnable action) ?
Difference between Handler.post(Runnable r) and Activity.runOnUiThread(Runnable r)
The difference between
Activity.runOnUiThread()
andHandler.post(Runnable r)
is that therunOnUiThread
only executes a specific action from a thread that you are executing on a view (a component, be it TextView or another) of the main thread , that is, a component of your app.The Handler.post(Runnable r), basically serves the same purpose, but there is a small difference and that is that with Handler.post() you can access the components or variables of other threads and not only the main thread as with
runOnUiThread
.If you only want to modify a component of the main thread, I recommend that you use it
runOnUiThread()
since that way you will not have problems.An example usage of
runOnUiThread()
is:An example usage of
Handler.post(Runnable r)
is:Another thing is to use
AsyncTask
, which has specific methods to be able to create actions in the main thread, but not be able to access its components, for example, oneAsycnTask
can use its methods to create a dialog with a process bar and act on it, but not will be able to access aTextView
the main thread.I give an example:
I hope I have helped you with your question. If you have any other questions or do not understand something I am explaining, please leave me a comment and I will clarify it for you.
Good luck!!