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

Android 應用開發:Thread 與 Handler 的搭配使用

編輯:關於 Android 程式設計

在 Android 中,耗時操作必須放在背景執行緒執行,而更新 UI 則需透過 Handler 將訊息回傳主執行緒。以下以一個模擬進度條遞增的範例,說明 Thread 與 Handler 的協作方式。

ThreadHandlerDownActivity.java:

package cn.sanbo.test.threadhandler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class ThreadHandlerDownActivity extends Activity implements
        View.OnClickListener {

    private TextView textView;
    private boolean isExits = false;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int jd = (Integer) msg.obj;
            if (jd == 100) {
                textView.setText("耗時完成!");
            } else {
                textView.setText("耗時完成:" + jd + "%");
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    private void init() {
        this.findViewById(R.id.btnThread).setOnClickListener(this);
        textView = (TextView) this.findViewById(R.id.tv_content);
    }

    public void onClick(View v) {
        if (v.getId() == R.id.btnThread) {
            if (!isExits) {
                isExits = true;
                new MyThread().start();
            } else {
                Toast.makeText(ThreadHandlerDownActivity.this, "耗時操作進行中,請等待~", 0).show();
            }
        }
    }

    class MyThread extends Thread {
        public void run() {
            super.run();
            boolean isGoOn = true;
            int jd = 0;
            while (isGoOn) {
                try {
                    jd++;
                    sleep(30);
                    Message msg = new Message();
                    msg.obj = jd;
                    handler.sendMessage(msg);
                    if (jd == 100) {
                        isGoOn = false;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

版面配置 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">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/btnThread"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="threadhandler" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="down "
        android:textColor="@android:color/white"
        android:gravity="center"
        android:textSize="25sp"
        android:id="@+id/tv_content"/>
</LinearLayout>

運作原理

  • 點擊按鈕後啟動背景執行緒 MyThread,透過 isExits 旗標避免重複啟動。
  • 背景執行緒在迴圈中累加進度值 jd,並以 Message.obj 攜帶數值,透過 handler.sendMessage() 送回主執行緒。
  • 主執行緒的 handleMessage() 接收到訊息後,即可安全地更新 TextView 的內容,達到即時反映進度的效果。

這種 Thread + Handler 的模式是 Android 早期常見的 UI 更新做法。在現代開發中,也可改用 AsyncTask(已不建議)、Kotlin 協程或 LiveData 等更簡潔的方案來達成相同目的。

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