編輯:關於 Android 程式設計
幾乎每個 App 遲早都會遇到「從網路抓一個檔案存到本機」的需求:電子書、MP3、圖片、更新包都算。本文示範一个不依賴第三方函式庫的基礎寫法,用 HttpURLConnection 取串流,再逐段寫入外部儲存空間,並把職責拆成三個類別。
download(String urlStr) 處理純文字回應,逐行讀回字串;downfile(String urlStr, String path, String fileName) 處理二進位檔案,回傳整數狀態碼。<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
少了 INTERNET 權限,連線會在建立 socket 時直接失敗;少了寫入權限,檔案會在開啟輸出流時丟出例外。兩者缺一不可。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android_hello word" />
<Button
android:id="@+id/buttontxt"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="單擊下載 txt 文件" />
<Button
android:id="@+id/buttonmp3"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:text="單擊下載 mp3 文件" />
</LinearLayout>
public class HttpDownloader {
private URL url = null;
/** 下載純文字內容 */
public String download(String urlStr) {
StringBuilder sb = new StringBuilder();
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
reader = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) try { reader.close(); } catch (IOException ignored) {}
if (conn != null) conn.disconnect();
}
return sb.toString();
}
/**
* 下載二進位檔案
* @return -1 下載失敗;0 成功;1 檔案已存在
*/
public int downfile(String urlStr, String path, String fileName) {
FileUtils fileUtils = new FileUtils();
if (fileUtils.isExist(path + fileName)) {
return 1;
}
InputStream in = null;
try {
in = getFromUrl(urlStr);
File file = fileUtils.writeToSDPATHFromInput(path, fileName, in);
return file != null ? 0 : -1;
} catch (IOException e) {
e.printStackTrace();
return -1;
}
}
/** 依 url 取得輸入流 */
public InputStream getFromUrl(String urlStr) throws IOException {
url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
return conn.getInputStream();
}
}
兩個方法背後其實是同一件事——取得 InputStream,差別只在「怎麼消化這個串流」:文字用 BufferedReader 逐行讀,檔案則原封不動寫到磁碟。相較於原範例,這裡補上了逾時設定與 finally 中的資源釋放,這兩點在真實環境中經常是 ANR 與記憶體洩漏的來源。
public class FileUtils {
private String SDPATH = null;
public FileUtils() {
SDPATH = Environment.getExternalStorageDirectory() + "/";
}
public String getSDPATH() { return SDPATH; }
public File createFile(String fileName) throws IOException {
File file = new File(SDPATH + fileName);
file.createNewFile();
return file;
}
public File createDir(String fileName) throws IOException {
File dir = new File(SDPATH + fileName);
dir.mkdir();
return dir;
}
public boolean isExist(String fileName) {
return new File(SDPATH + fileName).exists();
}
public File writeToSDPATHFromInput(String path, String fileName,
InputStream inputstream) {
File file = null;
OutputStream out = null;
try {
createDir(path);
file = createFile(path + fileName);
out = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = inputstream.read(buffer)) > 0) {
out.write(buffer, 0, length); // 只寫入實際讀到的長度
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputstream != null) inputstream.close();
if (out != null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
}
這裡有個細節值得留意:迴圈條件必須是 (length = in.read(buffer)) > 0 搭配 out.write(buffer, 0, length)。若直接寫 out.write(buffer),每次都會把整個 1024 位元組寫出去,最後一段沒填满的空白位元組會讓檔案尾端多出一堆垃圾——圖片因此打不開、壓縮檔因此解不開,都是這個原因。
public class Download extends Activity {
private Button buttontxt;
private Button buttonmp3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
buttontxt = (Button) findViewById(R.id.buttontxt);
buttontxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
HttpDownloader hd = new HttpDownloader();
String txt = hd.download("https://www.example.com/");
Log.i("Download", txt);
}
}).start();
}
});
buttonmp3 = (Button) findViewById(R.id.buttonmp3);
buttonmp3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
HttpDownloader hd = new HttpDownloader();
int result = hd.downfile(
"https://www.example.com/demo.jpg",
"Android/", "9.jpg");
Log.i("Download", "result = " + result);
}
}).start();
}
});
}
}
NetworkOnMainThreadException。所以下載一定要放在背景執行緒,這也是範例為何要包一層 new Thread()。Handler、runOnUiThread()、AsyncTask(已不建議)或 Kotlin 協程切回主執行緒。Environment.getExternalStorageDirectory() 會受限;建議改用 getExternalFilesDir() 取得 App 專屬目錄(不需額外權限),或透過 MediaStore / SAF 存取共享媒體。Android 13 更把媒體權限細分為 READ_MEDIA_IMAGES 等。getInputStream() 在 4xx/5xx 時會丟例外,正式環境應先取 getResponseCode() 判斷,並用 getErrorStream() 讀取錯誤內容。path + fileName 若直接來自網路回應,可能被塞入 ../ 造成路徑穿越。檔名前應過濾非法字元並強制使用預期目錄。Content-Length 當分母;要支援續傳,則在請求中帶上 Range 標頭並以 append 模式開啟輸出流。DownloadManager 或 WorkManager 會比自行管理執行緒更省事,也能在 App 被關閉後繼續。
用 TabLayout 打造類微信底部導航欄的實作方法
以前做專案大多用 RadioButton 來切換,這次改用 TabLayout 來實現頁籤切換的效果。 目標是做出一個類似 QQ、微信那種頁面(也就是 Fragment
Android 插件化初探:仿 QQ 一鍵換膚,思考比實作更重要
群裡有人點題,說想寫一篇關於插件化的文章。老實說我對插件化也算不上精通,於是想了個折衷辦法:先別急著上 DynamicLoadApk 那一類完整框架,而是從「換膚」這個最
Android 逐幀動畫 FrameAnimation:XML 與程式碼兩種定義方式
逐幀動畫(Frame By Frame)是最直覺的動畫形式:把一連串關鍵幀依序播放,就形成動畫。它的優點是彈性極高,幾乎能表現任何內容,而且類似電影的播放模式特別適合細膩
用 ViewPager 做出類似 QQ 的分頁切換效果
這幾天在研究 ViewPager,順手做了一個類似 QQ「最近聯繫人、好友、群組」那樣的分頁切換效果(至於 QQ 本身是否也用它實作,就不得而知了)。 ViewPager