編輯:關於 Android 程式設計
AsyncTask 雖然已經被標記為過時,但它「後台幹活、前台刷新」的模型依然是理解 Android 線程通信的好教材,做個帶進度條的下載示例非常合適。下面逐段講解。
package com.example.downloadfile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class DownloadFile extends Activity {
public static final String LOG_TAG = "test";
private ProgressDialog mProgressDialog;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
File rootDir = Environment.getExternalStorageDirectory();
// 定義要下載的文件名
public String fileName = "test.jpg";
public String fileURL = "https://lh4.googleusercontent.com/-HiJOyupc-tQ/TgnDx1_HDzI/AAAAAAAAAWo/DEeOtnRimak/s800/DSC04158.JPG";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Android Download File With Progress Bar");
// 檢查下載目錄是否存在
checkAndCreateDirectory("/mydownloads");
// 執行 asynctask
new DownloadFileAsync().execute(fileURL);
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
@Override
protected String doInBackground(String... aurl) {
try {
// 連接地址
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
// 計算文件長度
int lenghtOfFile = c.getContentLength();
FileOutputStream f = new FileOutputStream(new File(rootDir + "/my_downloads/", fileName));
InputStream in = c.getInputStream();
// 下載的代碼
byte[] buffer = new byte[1024];
int len1 = 0;
long total = 0;
while ((len1 = in.read(buffer)) > 0) {
total += len1;
// total = total + len1
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d(LOG_TAG, e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d(LOG_TAG, progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String unused) {
// 文件下載完成後關閉對話框
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
public void checkAndCreateDirectory(String dirName) {
File new_dir = new File(rootDir + dirName);
if (!new_dir.exists()) {
new_dir.mkdirs();
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
// we set this to 0
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
}
要點在於 AsyncTask 的三個回調分工:onPreExecute 在主線程彈出進度框;doInBackground 在子線程讀流寫文件,並用 publishProgress 把百分比拋出去;onProgressUpdate 回到主線程刷新進度;onPostExecute 收尾關閉對話框。這種「後台計算、前台更新」的分工正是它適合做下載的原因。
注意一定要開啟網絡與寫存儲的權限:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.downloadfile"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="4" />
<application
android:icon="@drawable/icon"
android:label="@string/app_name">
<activity
android:name=".DownloadFile"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
實戰中建議把 HttpURLConnection 換成 OkHttp 並加上超時與斷點續傳,同時注意 Android 10 以後的分區存儲限制,寫入路徑需要相應調整。
感謝閱讀,希望能幫助到大家。
Android 實現透明狀態欄的詳解教程
現在越來越多 App 採用了透明狀態欄,效果確實很出彩。本文記錄一下實現過程,方便以後使用。先來看看要達到的效果: 其實原理很簡單:把 StatusBar 背景變成透
Android Studio 實戰:手動導入第三方 module 與本地類庫
把網友的 XMPP 範例專案從 ADT 搬遷到 Android Studio 時,發現它依賴一個放在 lib 目錄下的第三方類庫。直接用 Import Project 匯
Android記憶體快取算法解析:從LRU、LFU到ImageLoader實作
前言 在Android圖片加載與資料快取場景中,記憶體快取扮演關鍵角色。適當的快取能減少重複加載,提高使用者體驗;但若策略不當,也可能造成記憶體壓力。本文以常見快取演算法
MUI組件詳解(三):列表、遮罩蒙版、數字輸入框、側滑導航與彈出菜單
本篇聚焦MUI的五個常用組件:列表、遮罩蒙版、數字輸入框、側滑導航和彈出菜單,逐一說明其結構與用法。 一、List(列表) 列表是最常用的UI控件之一。MUI封裝的列表很