Android 規定只有主線程能更新 UI,因此耗時運算通常得放到子線程,再把結果回傳主線程刷新介面。本範例展示如何以 Handler + Looper + Message 的組合,讓子線程每隔一秒非同步更新標題,同時不影響主線程對按鈕的正常操作。
首先是 main.xml 版面配置:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/btnFirst"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="按鈕1" >
- </Button>
-
- <Button
- android:id="@+id/btnSecond"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="按鈕2" >
- </Button>
-
- </LinearLayout>
程式碼如下:
- package com.liujin.game;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Looper;
- import android.os.Message;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
-
- public class TestHandlerImage extends Activity implements OnClickListener {
- private Button btnFirst, btnSecond;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnFirst = (Button) this.findViewById(R.id.btnFirst);//得到按鈕
- btnSecond = (Button) this.findViewById(R.id.btnSecond);
- btnFirst.setOnClickListener(this);//設置監控
- btnSecond.setOnClickListener(this);
- MyThread myThread = new MyThread();//開啟子線程
- myThread.start();
-
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.btnFirst:
- btnFirst.setText("我點擊按鈕1");
- btnSecond.setText("等待點擊");
- break;
- case R.id.btnSecond:
- btnFirst.setText("等待點擊");
- btnSecond.setText("我點擊按鈕2");
- break;
- }
- }
-
- class MyThread extends Thread {
- TitleEventHandler handler;
- public int sleepTime=1000;
- public int Interval=0;
- public void run() {
- Looper mainLooper = Looper.getMainLooper();//得到主線程的Looper
- handler = new TitleEventHandler(mainLooper);
- handler.removeMessages(0);
- Message msg = null;
- Long start,end;
- int time = 15;
- while (true) {//定時每秒發送一個消息給主線程
- try {
- time--;
- start=System.currentTimeMillis();
- msg = handler.obtainMessage(1, 1, 1, "當前還剩" + (time + 1) + "秒");
- handler.sendMessage(msg);//發送消息
- end=System.currentTimeMillis();
- Interval=(int) (end-start);
- if(Interval<sleepTime){//定時睡眠
- Thread.sleep(sleepTime-Interval);
- }
- } catch (InterruptedException e) {
- }
- }
- }
- }
-
- class TitleEventHandler extends Handler {
- public TitleEventHandler() {
- super();
- }
-
- public TitleEventHandler(Looper looper) {
- super(looper);
- }
-
- @Override
- public void handleMessage(Message msg) {
- super.handleMessage(msg);
- setTitle((String) msg.obj);
- }
- }
- }
重點在於:子線程透過 Looper.getMainLooper() 取得主線程的 Looper 來建立 Handler,如此便能將訊息投遞到主線程,再由 handleMessage() 安全地呼叫 setTitle 更新介面,而主線程仍能同時正常響應按鈕點擊。