I have a class that inherits from Runnable

public class SentZip implements Runnable { @Override public void run() { while (true){ } } 

and there is a main in which I run this runnable through a handler

 public class MainActivity extends AppCompatActivity { Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); handler = new Handler(); } public void send1(View view) { handler.post(new SentZip()); } public void send2(View view) { Thread thread = new Thread(new SentZip()); thread.start(); } 

And for the test I hung on the ProgressBar screen so that it spins and shows the screen freezes or not ...

And when I launch the send1 method, the screen hangs, and when send2 is not ... It seems that the Handler is running correctly, why does it occupy the main thread?

This is what happens with the Handler.

 public void send(View view) { HandlerThread handlerThread = new HandlerThread("one", HandlerThread.NORM_PRIORITY); Looper mLooper = handlerThread.getLooper(); ----> Handler handler = new Handler(mLooper); handler.post(new SentZip()); handlerThread.start(); } 

    1 answer 1

    Because Handler executes the Runnable in the thread to which its Looper is attached, and the default constructor new Handler() creates a Handler with the Looper 'thread of which it was called.


    In general, that's how it should be

     public void send(View view) { HandlerThread handlerThread = new HandlerThread("one", HandlerThread.NORM_PRIORITY); handlerThread.start(); // только после этого у потока появится лупер Handler handler = new Handler(handlerThread.getLooper()); handler.post(new SentZip()); } 
    • How do I tell Looper to work correctly? - Aleksey Timoshchenko
    • one
      Well in your case correctly send2. Sense to use Handler I do not see. And in general, to run rasnabl in a separate thread, you need to create this stream using the HandlerThread class, start it, and then use its looper when creating the handler. - xkor
    • I added to the answer as you said, but it still does not work for me ... What did I do wrong? - Aleksey Timoshchenko
    • one
      @AlekseyTimoshchenko you forgot to make handlerThread.start(); after creating the thread. - xkor
    • Added changes to the question, but still does not work ((This is the error that Caused by writes: java.lang.NullPointerException: Attempt to read from the field 'android.os.MessageQueue android.os.Looper.mQueue' on a null object reference - Aleksey Timoshchenko