Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 基礎總結(十五):Handler 詳解(下)——從消息系統原理到實戰

編輯:關於 Android 程式設計

要真正理解 Android 的消息機制,Looper、Handler、MessageQueue 這些名字不能死背,得從「消息系統為何這樣設計」這個源頭看起。只有回到源頭,才能看清設計者的意圖與技術路線。

一、消息系統的基本原理

從一般系統設計的角度看,一個消息循環系統需要具備幾個要素:

消息佇列、發送消息、讀取消息、分發消息,以及承載這個循環的執行緒。

先看最基礎的消息驅動模型:

應用程式持續輪詢自己的消息佇列,一旦有消息進來,就依消息型別與參數交給對應的處理函式。要讓系統運作起來,必然同時存在消息的生產與消費。

生產者執行緒把消息放進佇列,消費者執行緒取出並處理。但這個最樸素的模型對真實系統來說並不夠 —— 當佇列為空時,消費者若持續空轉,會白白耗掉 CPU。於是我們加上一個旗語(semaphore):佇列為空時消費者進入掛起,等消息抵達時再被喚醒。

二、Android 的消息模型

Android 用 Looper、MessageQueue、Handler 這幾個概念搭出了消息系統。從上一節的原理可知,這些都是包裝;本質不變,仍然是「消息佇列中的分發路徑」與「分發處理方式的設計」。Android 巧妙地用物件抽象技術抽出了 Looper 與 Handler,再透過 View 的處理函式框架,把消息分發做得相當完整。

Android 消息系統的消息分發框架:

三、Looper 與 Handler 詳解

Looper 只負責建立消息循環的骨架:它建立消息佇列並掛到執行緒的上下文中,然後進入「取消息、分發消息」的迴圈。

Handler 則在同一個執行緒上下文中取得消息佇列,對它進行封裝操作,主要提供 SendMessage 這樣的入口,並肩負 dispatchMessage 這個實際派送工作。外部系統若要向某個 Android 執行緒發送消息,必須透過屬於該執行緒的 Handler。

Handler 屬於哪個執行緒,取決於它在哪個執行緒中被建立。建構時它做了兩件預設動作:從執行緒上下文取得 Looper,再透過 Looper 取得消息佇列並記錄在自己的 mQueue 成員裡。之後對外提供兩條主要路徑:

post(Runnable r) —— 放進佇列時會插到前方,執行時直接回呼 Runnable:

public final boolean post(Runnable r) {
    return sendMessageDelayed(getPostMessage(r), 0);
}

sendMessage(Message msg) —— 排在時間已到達的所有 post 訊息之後:

public final boolean sendMessage(Message msg) {
    return sendMessageDelayed(msg, 0);
}

dispatchMessage —— 派送時若訊息帶有 callback 就執行 callback,否則走預設的 handleMessage。實務上多半會覆寫 handleMessage 來處理自訂邏輯。另外,幾乎每個 Message 在送出時都會指定 target,也就是 Message.target = this。

Looper 究竟跑在哪裡?

從呼叫堆疊可以很直觀地看出它的位置:

NativeStart.main()
  ZygoteInit.main
    ZygoteInit$MethodAndArgsCall.run
      ActivityThread.main()
        Looper.loop()
          ViewRoot$RootHandler.dispatch()
            handleMessage
              ...

四、用 Handler 更新進度條

理解 Handler 之後,多執行緒的更新就不再是一團混亂。以下用「線程 + Handler」更新 ProgressBar:

public class Main extends Activity {
    ProgressBar pb1;
    Handler handle = new Handler();
    Button b1, b2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        pb1 = (ProgressBar) findViewById(R.id.pb1);
        pb1.setProgress(0);
        b1 = (Button) findViewById(R.id.b1);
        b1.setOnClickListener(b1Lis);
        b2 = (Button) findViewById(R.id.b2);
        b2.setOnClickListener(b2Lis);
    }

    private OnClickListener b1Lis = new OnClickListener() {
        @Override public void onClick(View v) { handle.post(add); }
    };

    private OnClickListener b2Lis = new OnClickListener() {
        @Override public void onClick(View v) {
            handle.removeCallbacks(add);
            pb1.setProgress(0);
        }
    };

    int pro = 0;
    Runnable add = new Runnable() {
        @Override
        public void run() {
            pro = pb1.getProgress() + 1;
            pb1.setProgress(pro);
            setTitle(String.valueOf(pro));
            if (pro < 100) {
                handle.postDelayed(add, 500);   // 未滿 100 就延遲 500ms 再跑一次
            }
        }
    };
}

五、在 Notification 中顯示進度條

官方文件提到 Notification 可以放進度條,於是動手做了一個下載進度的範例。做法是先用 RemoteViews 定義自訂版面,再在 Handler 中更新並重新 notify。

自訂版面 custom_dialog.xml:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#880490ff"
    android:orientation="horizontal"
    android:padding="10dp">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" />

    <ProgressBar
        android:id="@+id/pb"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="180dip"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#ff0000"
        android:textSize="16px" />
</LinearLayout>

Activity 中的邏輯:

public class MainActivity extends Activity {
    private int progress = 0;
    private RemoteViews view;
    private Notification notification = new Notification();
    private NotificationManager manager;
    private Intent intent;
    private PendingIntent pIntent;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            view.setProgressBar(R.id.pb, 100, progress, false);
            view.setTextViewText(R.id.tv, "下載" + progress + "%");
            // 關鍵:不重新 notify,進度條不會更新
            notification.contentView = view;
            notification.contentIntent = pIntent;
            manager.notify(0, notification);
            super.handleMessage(msg);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        view = new RemoteViews(getPackageName(), R.layout.custom_dialog);
        intent = new Intent(MainActivity.this, NotificationService.class);
        pIntent = PendingIntent.getService(MainActivity.this, 0, intent, 0);

        Button button = (Button) findViewById(R.id.bt);
        button.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification.icon = R.drawable.icon;   // 圖示必填,否則通知不顯示
                view.setImageViewResource(R.id.image, R.drawable.icon);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 0; i < 20; i++) {
                            progress = (i + 1) * 5;
                            try {
                                if (i < 19) { Thread.sleep(1000); }
                            } catch (InterruptedException e) { e.printStackTrace(); }
                            handler.sendMessage(new Message());
                        }
                    }
                }).start();
            }
        });
    }
}

執行結果:

六、用執行緒改變 Button 內容

這個例子示範了 Handler 的兩個核心用途:一是排程執行 Message 與 Runnable,二是讓某個動作跨執行緒執行。可用的排程方法包括 post 系列的 post(Runnable)、postAtTime、postDelayed,以及 sendMessage 系列的 sendEmptyMessage(int)、sendMessage、sendMessageAtTime、sendMessageDelayed。

public class MyHandlerActivity extends Activity {
    Button button;
    MyHandler myHandler;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handlertest);
        button = (Button) findViewById(R.id.button);
        myHandler = new MyHandler();
        new Thread(new MyThread()).start();
    }

    /** 與主執行緒一起運行,負責接收並處理訊息 */
    class MyHandler extends Handler {
        public MyHandler() { }
        public MyHandler(Looper L) { super(L); }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 這裡可以安全更新 UI
            Bundle b = msg.getData();
            String color = b.getString("color");
            MyHandlerActivity.this.button.append(color);
        }
    }

    class MyThread implements Runnable {
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) { e.printStackTrace(); }

            Message msg = new Message();
            Bundle b = new Bundle();
            b.putString("color", "我的");
            msg.setData(b);
            MyHandlerActivity.this.myHandler.sendMessage(msg);
        }
    }
}

七、每 5 秒自動更新標題

同樣是 Handler 的排程能力,這次搭配 Timer 週期性觸發:

public class HandlerDemo extends Activity {
    private int title = 0;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    updateTitle();
                    break;
            }
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTask(), 1, 5000);
    }

    private class MyTask extends TimerTask {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            mHandler.sendMessage(message);
        }
    }

    public void updateTitle() {
        setTitle("Welcome to Mr Wei's blog " + title);
        title++;
    }
}

小結

Handler 之所以好用,是因為它把「排程」與「跨執行緒溝通」這兩件麻煩事收在一個物件裡。理解 Looper 的循環、MessageQueue 的排序、Handler 的派送之後,多執行緒的更新就不再需要靠猜,而是能清楚掌握每一段程式碼在哪條執行緒上跑、又準備把結果交給誰。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved