How to use runOnUiThread()

Asked

Viewed 2,013 times

5

I’m studying the use of Threads, aSynkTasks and Handlers and came across this method, runOnUiThread()

  • How does this method become a repetitive process to the point of replacing Handler? How this method works?

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


runOnUiThread(new Runnable())
public void run(){
// alguma coisa}

1 answer

6


Definition of the method:

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

So come on:

  • How does this method become a repetitive process to replace Handler? How does this method work?

I believe it does not replace Handler, because they have different functionalities!

The runOnUiThread, sends a Runnable to run in the UI Thread, while the Handler, executes a Runnable in a future time (predefined) or executes this Runnable in a Thread different (not only the UI as 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 explains how it works!

Now we come to the definition of Runnable :

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

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

Documentation of the runOnUiThread method

Documentation of the Handler Class

Documentation of the Runnable interface

  • great explanation :) is that in the example of the book I saw it uses as a substitute for Handler... so that if it calls this method does not need a Handler for other things... thank you!

  • 2

    So that’s why I believe that does not replace, Handler has several uses, and one of it is very similar to what the 'runOnUiThread' method does!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.