android之handler

來源:互聯網
上載者:User

標籤:android   handler   thread   

android中handler的基本使用方法以及運行原理。

最近看mars的android重設版第二季的視頻關於handler的講解,讓我對於這個以前知道怎麼用,卻不是很明白原理的組件的理解瞬間加深了無數倍。mars真的講的很好,視頻真的都蠻不錯的。下面我寫寫自己學習到的知識,以及自己的瞭解。

  1. handler的基本運行原理
  2. handler怎樣從worker thread傳輸資料到main thread
  3. handler怎樣從main thread傳輸資料到worker thread
  4. handler的post()方法
handler的基本運行原理

為什麼我們需要一個handler?我想這是一個最重要的問題,也就是說handler的作用到底是什嗎?handler主要是用於線程間的通訊,那麼問題又來了,為什麼一個app中需要多個線程,而不是只有一個UI主線程就可以了呢?

假如app中只有一個UI主線程,那麼,當需要進行網路連接,網路下載這些等待耗時較長的任務時,android系統就會檢測到UI主線程長時間沒有響應,就會發出一個 application not response的異常警告,簡稱ANR問題。所以,在UI主線程中,是要與使用者即時互動的,不能出現長時間的等待問題。於是,這些任務必須在worker thread中進行。

然而根據android的設定,UI主線程之外的線程,(除了特別的控制項,例如progressbar)不能修改UI裡的控制項的,這樣又出現了新的問題,我們在子線程獲得的資料,該如何反應的UI上與使用者進行互動?這樣,就出現了這個巧妙的組件,handler!

那麼,handler到底是如何啟動並執行呢?handler對象首先取出一個訊息對象,存入到一個訊息佇列messagequeue中,然後在另外一端,有一個looper對象,迴圈的從訊息佇列中取出訊息對象再交給handler去處理。

handler怎樣從worker thread傳輸資料到main thread
public class MainActivity extends ActionBarActivity {    private Handler handler;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button) findViewById(R.id.cancleButton);//    點擊button啟動新線程        button.setOnClickListener(new OnClickListener() {            public void onClick(View arg0) {                Thread thread = new Mythread();                thread.start();            }        });        handler = new Myhandler();    }//  複寫hanlder中的handlerMessage方法,處理從訊息佇列中得到的訊息    class Myhandler extends Handler{        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            String s = msg.obj.toString();            System.out.println("在當前線程中"+Thread.currentThread().getName()+"獲得來自這個線程的訊息"+s);        }    }//  在worker thread中使用handler.obtainMessage()方法得到一個Message對象,再把訊息存入message中,發入訊息佇列    class Mythread extends Thread{        @Override        public void run() {            Message msg = handler.obtainMessage();            msg.obj = currentThread().getName();            handler.sendMessage(msg);        }    }}

通過這個例子,我們可以看到,handlerMessage()方法是運行在主線程中的,而他可以得到來自worker thread的訊息,這樣,就可以將訊息在UI介面更新了。

為什麼只是初始化了一個handler對象,就會自動調用他的handleMessage方法?是因為在android.os.Handler類中有一個looper對象,會迴圈的從訊息佇列中取出訊息,調用handleM而是撒個方法。

handler怎樣從main thread傳輸資料到worker thread
public class MainActivity extends ActionBarActivity {    private Handler handler;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button) findViewById(R.id.cancleButton);//      每點擊一次button,給worker thread 發送一個訊息        button.setOnClickListener(new OnClickListener() {            public void onClick(View arg0) {//              在main中使用handler.obtainMessage()方法得到一個Message對象,再把訊息存入message中,發入訊息佇列                Message msg = handler.obtainMessage();                msg.obj = Thread.currentThread().getName();                handler.sendMessage(msg);            }        });        Thread thread = new Mythread();        thread.start();    }//  複寫hanlder中的handlerMessage方法,處理得到的訊息    class Myhandler extends Handler{        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            String s = msg.obj.toString();            System.out.println("在當前線程中"+Thread.currentThread().getName()+"獲得來自這個線程的訊息"+s);        }    }//  work thread 接受這個訊息,並調用handleMeesage()方法處理訊息    class Mythread extends Thread{        @Override        public void run() {//      looper對象的loop方法從訊息佇列中取出訊息,調用handleMeesage()方法處理訊息            Looper.prepare();            handler = new Myhandler();            Looper.loop();        }    }}

通過運行結果可以知道,handleMessage()方法運行在worker thread中,這樣就可以在worker thread中處理來自主線程的訊息,實現了進程間的通訊。

handler的post()方法

post方法通過產生一個message,然後把Runnable對象放在message中,再把message放在訊息佇列中,然後在主線程中取出這個Runnable對象,在主線程中執行。

public class MainActivity extends ActionBarActivity {    private Handler handler;    private Button button;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button) findViewById(R.id.cancleButton);//      初始化handler,處理得到的Runnable對象        handler = new Handler();//      點擊按鈕執行worker thread        button.setOnClickListener(new OnClickListener() {            public void onClick(View arg0) {                Thread thread = new Mythread();                thread.start();            }        });    }    class Mythread extends Thread{        @Override        public void run() {//          在worker thread 中初始化一個Runnable對象            Runnable runnable = new Runnable() {                public void run() {//          列印出該Runnable方法執行的線程                        System.out.println("當前線程名"+Thread.currentThread().getName());                }            };//          post該Runnable對象            handler.post(runnable);        }    }}

最後的結果,是這個Runnable對象執行在main線程中。有了post()方法,我們可以直接在worker thread中先產生一個Runnable對象,然後在其中寫上更新UI的代碼,直接用post方法即可更新UI。

android之handler

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.