【Android初級】如何實現一個「模擬後臺下載」的加載效果(附源碼)

在Android裏面,後臺的任務下載功能是很是經常使用的,好比在APP Store裏面下載應用,下載應用時,須要跟用戶進行交互,告訴用戶當前正在下載以及下載完成等。android

今天我將經過使用Android的原生控件 ProgressDialog 來實現一個「模擬後臺下載」的效果。實現思路以下:ide

  1. 用戶點擊按鈕,模擬開始下載佈局

  2. 顯示一個進度框,並修改後臺界面上的文字,告知用戶當前正在下載、須要等待post

  3. 開啓一個線程,模擬後臺下載任務,假設下載須要3秒鐘完成,讓該線程等待3秒this

  4. 線程執行完成後,關閉進度框,並更新界面上的文字,告知用戶下載完成線程

源碼以下:code

一、主Activityxml

`public class ProgressDialogDemo extends Activity {
private Button button;
private TextView textView;
private ProgressDialog mDialog;blog

@Override
protected void onCreate(Bundle onSavedInstance) {
    super.onCreate(onSavedInstance);
    setContentView(R.layout.progress_dialog_demo);

    button = findViewById(R.id.buttonProgressDialog);
    textView = findViewById(R.id.textView6);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // 建立並顯示進度加載框
            mDialog = ProgressDialog.show(ProgressDialogDemo.this,
                    "Please wait..",
                    "Calculating in the background...",
                    true);

            // 設置文字內容,告訴用戶當前正在後臺計算
            textView.setText("Calculating in the background...");

            new Thread() {
                @Override
                public void run() {
                    try {

                        // 模擬耗時的後臺計算
                        sleep(3000);
                    } catch (InterruptedException e) {

                    } finally {

                        // 耗時的後臺計算完成,關閉進度框,再次以文字的形式告訴用戶
                        mDialog.dismiss();
                        refreshTextView();
                    }
                }
            }.start();
        }
    });
}

private void refreshTextView() {
    textView.post(new Runnable() {
        @Override
        public void run() {

            // 須要在主線程去從新設置文字
            textView.setText("Done with calculating.");
        }
    });
}

}`源碼

二、佈局文件progress_dialog_demo.xml:

`

<TextView
        android:paddingTop="20dp"
        android:text="This is a progress dialog demo."
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:layout_height="wrap_content" android:id="@+id/textView6"/>
<Button
        android:text="Start Background Calculating"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/buttonProgressDialog"/>

`

三、效果圖以下:(注意看後臺界面上文字的變化)

不過,這個 ProgressDialog類從Android 8.0開始被廢棄了,由於這個類有個缺點是:
該框顯示時,用戶沒法跟應用進行交互。
建議使用 ProgressBar 或者通知 Notification代替,後面會分享 ProgressBar 的使用。

相關文章
相關標籤/搜索