編輯:關於 Android 程式設計
從網路下載資源再存到裝置上,是幾乎每個 App 都會用到的能力。流程可以拆成兩半:先拿到資料流,再把資料流寫進檔案系統。以下把整個過程整理成可重複使用的工具類別。
步驟一:建立 HttpURLConnection。
// urlStr 指的是網路位址 url = new URL(urlStr); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
步驟二:取得 InputStream。
InputStream input = null; input = urlConn.getInputStream();
步驟三:加上網路權限。
<uses-permission android:name="android.permission.INTERNET"/>
另外,Android 4.0 之後主線程禁止網路連線,這整段流程必須放在背景線程(AsyncTask、Thread 或 Coroutine)裡執行。
手機內容量有限,大量資料通常得放進外部儲存。不同機型的掛載點並不一致,因此要用系統 API 取得路徑,而不是硬編碼:
// 取得目前裝置外部儲存裝置的目錄 Environment.getExternalStorageDirectory();
寫入前同樣要宣告權限(Android 6.0 起需執行期動態申請):
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
這個類別封裝了 SD 卡上最常做的幾件事,之後要操作檔案直接拿來用:
public class FileUtils {
private String SDPATH;
public String getSDPATH() {
return SDPATH;
}
public FileUtils() {
// 取得外部儲存裝置的目錄
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
/**
* 在 SD 卡上建立檔案
*/
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
/**
* 在 SD 卡上建立目錄
*/
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdirs(); // 用 mkdirs 才能一次建立多層
return dir;
}
/**
* 判斷檔案是否存在
*/
public boolean isFileExist(String fileName) {
File file = new File(SDPATH + fileName);
return file.exists();
}
/**
* 把 InputStream 的內容寫入 SD 卡
*/
public File write2SDFromInput(String path, String fileName, InputStream input) {
File file = null;
OutputStream output = null;
try {
creatSDDir(path);
file = creatSDFile(path + fileName);
output = new FileOutputStream(file);
byte[] buffer = new byte[4 * 1024];
int len;
while ((len = input.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return file;
}
}
這裡有兩處對原始範例的修正。一是 mkdir() 改為 mkdirs(),前者無法建立多層目錄,會導致下載到巢狀路徑時靜默失敗。二是寫入迴圈改為 write(buffer, 0, len),原本直接 write(buffer) 會把緩衝區尾端的殘留資料一起寫進檔案,讓下載的圖片或壓縮檔損毀。
public class HttpDownloader {
private URL url = null;
private FileUtils fileUtils = new FileUtils();
/**
* @return 0 = 下載成功;1 = 檔案已存在;-1 = 下載失敗
*/
public int downfile(String urlStr, String path, String fileName) {
if (fileUtils.isFileExist(path + fileName)) {
return 1;
}
InputStream input = null;
try {
input = getInputStream(urlStr);
if (input == null) return -1;
File resultFile = fileUtils.write2SDFromInput(path, fileName, input);
return resultFile == null ? -1 : 0;
} catch (IOException e) {
e.printStackTrace();
return -1;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 取得 InputStream —— 所有檔案處理的前置動作,因此獨立成方法
*/
public InputStream getInputStream(String urlStr) throws IOException {
InputStream is = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setConnectTimeout(10000);
urlConn.setReadTimeout(10000);
is = urlConn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return is;
}
}
相較於原始版本,這裡補上了 finally 關流與連線逾時設定。前者避免檔案描述符洩漏,後者則能防止網路異常時 App 無限期卡住。
public class MainActivity extends Activity {
private Button downfile = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downfile = (Button) findViewById(R.id.downfile);
downfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 實際專案請把下載放到背景線程
HttpDownloader httpDownLoader = new HttpDownloader();
int result = httpDownLoader.downfile(
"https://192.168.1.100:8080/test/file.jpg", "test/", "test.jpg");
switch (result) {
case 0:
Toast.makeText(MainActivity.this, "下載成功!", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this, "已有檔案!", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(MainActivity.this, "下載失敗!", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
撰寫下載位址時千萬不要用 127.0.0.1 或 localhost。這個位址在手機上指向手機自己,而不是你的電腦。這個錯誤不會讓程式崩潰,它只會靜靜地下載失敗,然後你在 SD 卡裡翻半天找不到檔案——非常浪費時間。請改用電腦在區網中的實際 IP,並確認防火牆已放行該連接埠。
本範例以「檔案是否已存在」作為唯一的重試判斷,實務上應該搭配 ETag 或 Content-Length 做續傳與完整性驗證。另外,Android 10 之後推出了 Scoped Storage,直接寫入任意路徑的做法已受限,新專案請改用 MediaStore 或 SAF(Storage Access Framework)。下載機制本身也建議交給 WorkManager 或 DownloadManager,它們能處理中斷續傳、佇列排程與通知提示。
自製簽到日曆:用 onDraw 與 Path 打造自定義 CalendarView
前言 這篇文章的看點主要在源碼本身,程式碼裡的註解寫得相當詳細,直接讀源碼反而更好理解。因此本文著重說明組件的整體運作流程,並搭配關鍵程式碼片段來講解。 自定義 View
QQ 厘米秀故事卡怎麼集?取得方式與解鎖套路整理
厘米秀是手機 QQ 推出的虛擬形象玩法,除了角色動作互動,還加入了故事卡線索系統。集齊一套故事卡,可以換到對應的精美套裝。以下是常見問題的整理。 故事卡怎麼取得? Q:有
Android 入門:跑通第一個 OpenCV 程式
剛接觸 Android 開發時,由於先前對 OpenCV 較為熟悉,於是便想先在 Android 上把 OpenCV 跑起來。本文記錄了從環境配置到實現攝像頭即時影像處理
Android 動畫學習筆記(一):補間動畫四兄弟完全入門
前言:從剛接觸 Android 到現在,動畫始終是個繞不開的話題。它在實際專案裡的出現頻率遠比想像中高,而且只要用得好,介面的質感會立刻拉上一個檔次。但也常常遇到一種尷尬