How to use runOnUiThread()

I am studying using Threads, aSynkTasks and Handlers and came across this method, runOnUiThread ()

  • How does this method become a repetitive process to the point of replacing the handler?How does this method work?

  • I would like to understand how this method works and what the need to implement Runnable() inside this method as in this example:


runOnUiThread(new Runnable())
public void run(){
// alguma coisa}
Author: Daniel Gentil, 2017-04-06

1 answers

Method definition:

" performs the action specified in the UI Thread. If the current Thread is the UI Thread, then the action will be executed immediately. If the Thread the action is launched in the event queue."

So let's go:

  • How does this method become a repetitive process to the point of replacing the handler?How does this method work?

I believe not replaces Handler as they have different functionality!

The runOnUiThread, sends a Runnable to be executed in the UI Thread, while the Handler, executes a Runnable in a future (pre-defined) time or executes this Runnable in a different Thread (not just the UI like the runOnUiThread).

  • I would like to understand how this method works and what is the need to implement Runnable() within this method

I believe the above definition, explain the its working!

Now let's go to the definition of Runnable:

The Runnable interface must be implemented by any class whose instances are meant to be run by a Thread.

We use the Runnable to encapsulate and send the code that we want to transfer to be executed in another Thread.

Documentation of the runonuithread method

Class documentation Handler

Documentation of the Runnable interface

 6
Author: Thiago Luiz Domacoski, 2017-04-06 13:43:51