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

Android ProgressDialog 完整示例(含任務結束後關閉)

編輯:關於 Android 程式設計

網路上的進度條範例大多只示範「怎麼顯示」,很少提到「任務結束後怎麼關掉」。以下參考各方做法並實測後,整理出一份從顯示到關閉的完整範例。

ProgressBarDemo.java

package com.lveyo.android.demo.progressbar;

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

public class ProgressBarDemo extends Activity {

    private TextView statusTextView;
    private Button beginBtn;
    private ProgressDialog progressDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        statusTextView = (TextView) findViewById(R.id.status);
        beginBtn = (Button) findViewById(R.id.beginBtn);
        setListener();
    }

    /**
     * 用 Handler 更新 UI
     */
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 關閉 ProgressDialog
            progressDialog.dismiss();

            // 更新 UI
            statusTextView.setText("Completed!");
        }
    };

    /**
     * 按鈕事件
     */
    private void setListener() {
        beginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 顯示 ProgressDialog
                progressDialog = ProgressDialog.show(
                        ProgressBarDemo.this, "Loading...", "Please wait...", true, false);

                // 開啟背景執行緒
                new Thread() {
                    @Override
                    public void run() {
                        // 模擬耗時運算
                        Calculation.calculate(4);

                        // 通知 Handler
                        handler.sendEmptyMessage(0);
                    }
                }.start();
            }
        });
    }
}

Calculation.java

一個模擬耗時工作的類別:

package com.lveyo.android.demo.progressbar;

/**
 * 示意方法
 */
public class Calculation {

    public static void calculate(int sleepSeconds) {
        try {
            Thread.sleep(sleepSeconds * 1000);
        } catch (Exception e) {
            // 忽略中斷
        }
    }
}

版面配置 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

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

    <Button
        android:id="@+id/beginBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="begin" />

</LinearLayout>

為什麼一定要用 Handler

在 Android 中,只有建立 View 的那條執行緒(主執行緒,又稱 UI 執行緒)才能更新界面。背景執行緒若直接呼叫 setText(),會丟出 CalledFromWrongThreadException。

therefore 我們用 Handler:背景執行緒把訊息放進主執行緒的 MessageQueue,主執行緒在下一輪迴圈取出並執行 handleMessage,UI 更新就安全了。除了 Handler,也可以用 runOnUiThread()、View.post() 或 AsyncTask.onPostExecute() 達到同樣效果。

實務上更需要注意的幾件事

  1. ProgressDialog 已被標記為 deprecated(API 26 起)。Google 的理由是:這種強制區塊化、使用者無法互動又無法取消的設計,體驗並不好。現行專案建議改用 ProgressBar 放在版面配置中,搭配 SwipeRefreshLayout 或骨架屏呈現載入狀態。
  2. 务必在 onStop / onDestroy 中 dismiss。若背景任務還沒結束使用者就離開頁面,未關閉的 Dialog 會導致 WindowLeaked 錯誤。
  3. 記得支援取消。把 ProgressDialog.show() 的最後參數設為 true,並搭配 setOnCancelListener 中斷背景任務,讓使用者有掌控感。
  4. 若要顯示進度百分比,改用 ProgressDialog 的 setProgressStyle(ProgressDialog.STYLE_HORIZONTAL),並在背景執行緒中呼叫 progressDialog.incrementProgressBy()(此方法為執行緒安全)。

本範例的價值在於把「顯示 → 背景執行 → 通知主執行緒 → 關閉並更新 UI」這條完整閉環走過一遍,這個流程在改用任何現代 API 時都一樣成立。

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