201709013工作日記--Android訊息機制HandlerThread

來源:互聯網
上載者:User

標籤:ble   子線程   .post   family   rup   void   地方   log   封裝   

1.首先來看一個常規的handler用法:

在主線程中建立一個handler:

private Handler mHandler = new Handler() {        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            switch (msg.what) {                case 0:                    mTestTV.setText("This is handleMessage");//更新UI                    break;            }        }    };

 

在子線程中進行耗時操作,結束後發送訊息,主線程收到訊息後進行更新UI操作。

new Thread(new Runnable() {            @Override            public void run() {                try {                    Thread.sleep(1000);//在子線程有一段耗時操作,比如請求網路                    mHandler.sendEmptyMessage(0);                } catch (InterruptedException e) {                    e.printStackTrace();                }            }        }).start();

 

2.現在來看看handler.post()的版本:

private Handler mHandler;//全域變數@Overrideprotected void onCreate(Bundle savedInstanceState) {    mHandler = new Handler();    new Thread(new Runnable() {                @Override                public void run() {                    try {                        Thread.sleep(1000);//在子線程有一段耗時操作,比如請求網路                        mHandler.post(new Runnable() {                            @Override                            public void run() {                                mTestTV.setText("This is post");//更新UI                            }                        });                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }).start();

 

耗時操作完成之後,直接在handler開啟的子線程中進行了更新UI的操作。post和sendMessage原理都是封裝成Message,並且最終都調用了enqueueMessage()一個無限迴圈將訊息加入到訊息佇列中(鏈表的形式)。翻看MessageQueue的方法,我們找到了next(),代碼太長,不贅述,我們知道它是用來把訊息取出來的就行了。不過這個方法是在什麼地方調用的呢,不是在Handler中,我們找到了Looper這個關鍵人物,我叫他環形使者,專門負責從訊息佇列中拿訊息。參考部落格:http://blog.csdn.net/ly502541243/article/details/52062179/

 

201709013工作日記--Android訊息機制HandlerThread

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.