1

Please I am blocked with this concept of Handlers and Runnables in Android. Can someone please give me detailed explanation on Handlers and Runnables? Their syntax and implementation? I have read many articles on this but the concepts are not still clear and are even deployed in Java. Thanks in advance

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
BM egbe
  • 31
  • 1
  • 2
  • 1
    Possible duplicate of https://stackoverflow.com/questions/15136199/when-to-use-handler-post-when-to-new-thread . Whether it is Java or Kotlin isn't relevant. – EpicPandaForce Mar 10 '19 at 16:37

1 Answers1

5

I'm going to try to simplify so bear with me if it is not 100% accurate.

Basically, a Handler is used to communicate with a MessageQueue associated with a Thread. If you're on the main thread, or if you've called Looper.prepare() in the Thread that you're in, it has a Looper which is basically a holder for the MessageQueue.

This queue is constantly polled so that whenever a Message goes into it, it's dealt with on the Thread associated with this MessageQueue

If you're trying to execute a piece of code on a particular Thread, you have to use a Runnable. It is just an interface that has a void run() method which will be executed by the Looper, on its Thread.

Let's say you're doing a network request, you want it to happen on another Thread but when you get the result you somehow need to pass the data back to the Main Thread in order to update your UI because Views can't be modified from another Thread. You would do it like so:

// This will let you run method on main thread (even if you're not on main thread)
private final Handler handler = new Handler(Looper.getMainLooper());

// This will let you run method on background thread
private final Executor executor = Executors.newSingleThreadExecutor();


public void doSomething() {
    // posting to executor will go to background thread
    executor.post(new Runnable() {
        @Override
        public void run() {
            // This will now run on background thread
            // you can for example do network request here

            // posting to handler will go back to main thread
            handler.post(new Runnable() {
                @Override
                public void run() {
                    // This will execute on the Main Thread
                }
            });
        }
   });
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
Benoit TH
  • 601
  • 3
  • 12
  • 1
    Totally impressed that you took this question on and provided an answer that, if not exhaustive, is undoubtedly useful. Well done. – G. Blake Meike Mar 10 '19 at 16:50
  • I am more than grateful for the effort and time that you have used to clarify the used of these concepts. from here, I must be able to find my way. Thanks once more – BM egbe Mar 11 '19 at 12:40