2

As google says:

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

And i expect when i create a Handler in main thread (UI thread) it attached to this thread so it cause to freeze ui till end it's task. But in test this not happen and it is acts like it is on a backgound thread and do his task parallel. I used to create Handle like this:

 Handler mainHandler = new Handler(Looper.getMainLooper());

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            for (int i = 0; i < 35000; i++) {
                log.i(TAG,"log in Handler:"+i);
            }}
    };

    mainHandler.post(runnable);
    log.i(TAG,"log outSide");

In mainActivity (so handle should bound to Main thread). So what is the problem with this or am i create the handler in wrong way?

Some friends notice that doSomthing() is not complicated enough but why we see "log outSide" before "log in Handler:" if they are in a same thread.

Mahdi
  • 6,139
  • 9
  • 57
  • 109

2 Answers2

0

Actually, It's working as you expected, Your handler is currently associated with your main thread because it is created in it and your task is also running on the same. Try to add Thread.sleep(1000) method inside your for loop then you will see the freeze in your UI. Your current code runs with a complexity of O(1) since your N is constant, and your phone is capable enough to run this in a fraction of a second that's why you are not observing any freeze in your UI during the test.

0

Some friends notice that doSomthing() is not complicated enough but why we see "log outSide" before "log in Handler:" if they are in a same thread.

This is because of the delay in posting the Runnable to the Handler. Even though the Handler is created with the main thread's looper, there is still a small amount of delay between when post is called and when that Handler message is put into the Handler's queue and executed on the thread.

"log outside" runs instantaneously, so you see that log before the log within the Handler.

Mitch Ware
  • 415
  • 1
  • 4
  • 15