Android: Why can't I create a handler in new thread

后端 未结 4 1014
北荒
北荒 2020-12-14 01:11

I had a problem creating a handler in new thread. This is my code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(         


        
4条回答
  •  死守一世寂寞
    2020-12-14 01:38

    The Thread's lifecycle is finished right after run method returns. But since you are creating a Handler in this thread, the Handler needs the thread to be running for it to receive messages and process them.

    So for this to happen, run method should not exit. Hence you need a Looper to wait indefinitely and process messages that arrive to Handler.

    new Thread(new Runnable() {
            public void run() {
                Looper.prepare();
                Handler handler = new Handler();
                Looper.loop();
            }
        }).start();
    

提交回复
热议问题