【Android初級】如何實現一個「模擬後台下載」的載入效果(附源碼)
在Android裡面,後台的任務下載功能是非常常用的,比如在APP Store裡面下載應用,下載應用時,需要跟用戶進行交互,告訴用戶當前正在下載以及下載完成等。
今天我將通過使用Android的原生控制項 ProgressDialog 來實現一個「模擬後台下載」的效果。實現思路如下:
-
用戶點擊按鈕,模擬開始下載
-
顯示一個進度框,並修改後台介面上的文字,告知用戶當前正在下載、需要等待
-
開啟一個執行緒,模擬後台下載任務,假設下載需要3秒鐘完成,讓該執行緒等待3秒
-
執行緒執行完成後,關閉進度框,並更新介面上的文字,告知用戶下載完成
源碼如下:
1、主Activity
`public class ProgressDialogDemo extends Activity {
private Button button;
private TextView textView;
private ProgressDialog mDialog;
@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.");
}
});
}
}`
2、布局文件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"/>
`
3、效果圖如下:(注意看後台介面上文字的變化)
不過,這個 ProgressDialog類從Android 8.0開始被廢棄了,因為這個類有個缺點是:
該框顯示時,用戶無法跟應用進行交互。
建議使用 ProgressBar 或者通知 Notification代替,後面會分享 ProgressBar 的使用。