android handler和message的常用方法

來源:互聯網
上載者:User

1.

    private class AsyncServiceHandler extends Handler {

        AsyncServiceHandler(android.os.Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
                          ...........................................
                     case WifiManager.ENABLE_TRAFFIC_STATS_POLL: {
                          ...........................................

}

private AsyncServiceHandler mAsyncServiceHandler;

mAsyncServiceHandler = new AsyncServiceHandler(wifiThread.getLooper());

Message msg;

 msg = Message.obtain(mAsyncServiceHandler, WifiManager.ENABLE_TRAFFIC_STATS_POLL, 0, 0);

msg.sendToTarget();

這裡Message.obtain表示obtain Message object from the global pool, 第一個參數表示發送的handler目標,第二個為what, 第三個為arg1, 第四個為arg2,看函數原型就知道了:

    public static Message obtain(Handler h, int what, int arg1, int arg2) {
        Message m = obtain();
        m.target = h;
        m.what = what;
        m.arg1 = arg1;
        m.arg2 = arg2;

        return m;
    }
最後調用msg.sendToTarget()將訊息發送到AsyncServiceHandler中,AsyncServiceHandler繼承並重寫handleMessage方法,在handleMessage中根據switch處理接收到的訊息

2.

 Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;

            switch(what){

                case 2:

                          String shortFileNames = msg.getData().getString("packagename");

                           ........................自己的處理方法............................

            }

};

Message msg = mhandler.obtainMessage();
Bundle b = new Bundle();// 存放資料
msg.what = 2;
b.putString("packagename", shortfileNames.get(i));
msg.setData(b);
mhandler.sendMessage(msg); // 向Handler發送訊息,更新UI

原理和上面1其實是一樣的,也是從訊息池中擷取message,這樣不用新new一個,可以節省資源,new Bundle()用來存放資料,然後mhandler.sendMessage將訊息發送到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.