編輯:關於 Android 程式設計
幾乎每個 App 都逃不掉「從伺服器取檔案」這件事,可能是歌詞、音樂、圖片,也可能是設定檔。在 Android 上,最直覺的做法就是走 HTTP:開一條連線、拿到輸入串流,再把內容寫進外部儲存。本文用一個能同時下載歌詞檔與 MP3 的小範例,把整個流程走一遍。
核心只有三件事:建立連線物件、取得輸入串流、以及記得申明網路權限。
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();urlConn.getInputStream()android.permission.INTERNET下載的目的地通常是外部儲存。取得路徑的方式是 Environment.getExternalStorageDirectory(),對應的權限則是 android.permission.WRITE_EXTERNAL_STORAGE。若要在較新的 Android 版本上執行,還需要一併處理執行期權限的動態申請,這部分不在本範例範圍內,但實務上不可省略。
畫面上放兩個按鈕,一個抓歌詞、一個抓音樂。
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="下載歌詞" />
<Button
android:id="@+id/btn_mp3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/btn_txt"
android:text="下載 MP3" />
</RelativeLayout>
網路請求絕對不能寫在主執行緒,否則會直接觸發 NetworkOnMainThreadException。因此每個按鈕都對應一個獨立的工作執行緒。
package com.chay.download;
import com.chay.utils.HttpDownloader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private String urlStr_txt = "https://192.168.56.1:8080/mp3/wan.lrc";
private String urlStr_mp3 = "https://192.168.56.1:8080/mp3/wan.mp3";
private String path = "mp3/";
private String fileName = "wan.mp3";
private Button downloadTxtButton;
private Button downloadMp3Button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
downloadTxtButton = (Button) findViewById(R.id.btn_txt);
downloadTxtButton.setOnClickListener(new DownloadTxtListener());
downloadMp3Button = (Button) findViewById(R.id.btn_mp3);
downloadMp3Button.setOnClickListener(new DownloadMp3Listener());
}
/** 下載歌詞:文字檔可以直接轉成字串 */
class DownloadTxtListener implements OnClickListener {
@Override
public void onClick(View v) {
new DownloadTxtThread().start();
}
}
class DownloadTxtThread extends Thread {
@Override
public void run() {
HttpDownloader downloader = new HttpDownloader();
System.out.println(downloader.download(urlStr_txt));
}
}
/** 下載 MP3:二進位檔要落地成檔案 */
class DownloadMp3Listener implements OnClickListener {
@Override
public void onClick(View v) {
new DownMp3Thread().start();
}
}
class DownMp3Thread extends Thread {
@Override
public void run() {
HttpDownloader downloader = new HttpDownloader();
System.out.println(downloader.downFile(urlStr_mp3, path, fileName));
}
}
}
文字檔用 BufferedReader 逐行讀、拼成字串即可;二進位檔則是把串流原封不動地寫到檔案。這個類別刻意分成兩個方法,回傳值約定為:-1 表示失敗、0 表示成功、1 表示檔案已存在。
package com.chay.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpDownloader {
private URL url = null;
/** 下載純文字內容並直接回傳字串 */
public String download(String urlStr) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader buffer = null;
try {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (buffer != null) buffer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return sb.toString();
}
/** -1 失敗;0 成功;1 檔案已存在 */
public int downFile(String urlStr, String path, String fileName) {
InputStream inputStream = null;
try {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isFileExist(path + fileName)) {
return 1;
}
inputStream = getInputStreamFromUrl(urlStr);
File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream);
if (resultFile == null) {
return -1;
}
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
public InputStream getInputStreamFromUrl(String urlStr)
throws MalformedURLException, IOException {
url = new URL(urlStr);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
return urlConn.getInputStream();
}
}
這個工具類別負責三件事:判斷檔案是否存在、建立目錄與檔案、以及把輸入串流寫進外部儲存。寫入時用 4KB 的緩衝區迴圈搬資料,這是處理大檔最省內存的做法。
package com.chay.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.os.Environment;
public class FileUtils {
private String SDPATH;
public String getSDPATH() {
return SDPATH;
}
public FileUtils() {
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
public File creatSDFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
public File creatSDDir(String dirName) {
File dir = new File(SDPATH + dirName);
dir.mkdirs();
return dir;
}
public boolean isFileExist(String fileName) {
return new File(SDPATH + fileName).exists();
}
/** 把 InputStream 的內容整份寫進 SDCARD */
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 {
try {
if (output != null) output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return file;
}
}

整個下載機制其實很樸素:HttpURLConnection 取流、FileOutputStream 落地,中間用執行緒避開主執行緒。真正需要留意的是權限、路徑拼接與串流關閉這三個容易出錯的細節。若要進一步優化,可以加上進度回報、斷點續傳與失敗重試。
Android 自學筆記(六):動手做一個簡易簡訊發送器
用 SmsManager 做一個最小可用的簡訊發送器,是很適合入門的練習:元件少、流程清楚,還能順便學到長簡訊該怎麼處理。 版面配置 畫面很單純:一個輸入號碼的 E
設計模式筆記(6):適配器模式,Android UI 架構的靈魂
適配器模式(Adapter Pattern)是開發中出現頻率最高的模式之一——ListView 和 RecyclerView 的 Adapter 就是最直觀的例子。 生活
Android 進程啟動全流程:從 startProcessLocked 到消息循環
前言 分析完 Zygote 與 SystemServer 的啟動之後,自然該看看應用進程是怎麼被拉起來的。 前一篇提到過,Zygote 採用「復制自身」的方式創建進程。這
Android 實戰:為你的 App 接入 mob 短信驗證碼功能
一、前言 如今幾乎每個 App 都離不開短信能力,無論是用戶註冊還是消息通知,往往都要發一條短信出去。但對個人開發者而言,直接購買第三方短信服務的成本著實不低。好在 mo