What is the relationship between Looper, Handler and MessageQueue in Android?

前端 未结 5 1337
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 01:00

I have checked the official Android documentation/guide for Looper, Handler and MessageQueue . But I couldn\'t get it. I am new to and

5条回答
  •  时光说笑
    2020-11-28 01:17

    Extending the answer, by @K_Anas, with an example, As it stated

    It's widely known that it's illegal to update UI components directly from threads other than main thread in android.

    for instance if you try to update the UI using Thread.

        int count = 0;
        new Thread(new Runnable(){
            @Override
            public void run() {
                try {
                    while(true) {
                        sleep(1000);
                        count++;
                        textView.setText(String.valueOf(count));
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    
    
       ).start();
    

    your app will crash with exception.

    android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

    in other words you need to use Handler which keeps reference to the MainLooper i.e. Main Thread or UI Thread and pass task as Runnable.

      Handler handler = new Handler(getApplicationContext().getMainLooper);
            int count = 0;
            new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        while(true) {
                            sleep(1000);
                            count++;
                            handler.post(new Runnable() {
                               @Override
                               public void run() {
                                     textView.setText(String.valueOf(count));
                               }
                             });
    
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        ).start() ;
    

提交回复
热议问题