編輯:關於 Android 程式設計
下載檔案時當然要讓使用者看到進度。這個範例用 ProgressBar 搭配子執行緒,把下載百分比即時反映到介面上。過程中會踩到四個新手常碰到的問題,正好一起說明。
問題清單:
1、主執行緒中不能開啟網路連線,Toast 等也必須在主執行緒使用。
2、子執行緒不能直接修改 UI。
3、需要宣告網路權限。
4、暫停與繼續下載。
<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"
tools:context="com.dragon.android.textbar.MainActivity$PlaceholderFragment" >
<!-- progress 為當前進度;indeterminate 表示不確定模式,預設 false -->
<ProgressBar
android:id="@+id/progressBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:max="100"
android:progress="0"
android:indeterminate="true"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="startLoad"
android:layout_marginTop="86dp"
android:background="#009FEE"
android:text="@string/start"
android:textColor="#ffffff" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/progressBar1"
android:background="@null"
android:layout_alignParentLeft="true" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">hwdownload</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="start">開始</string>
<string name="stop">暫停</string>
<string name="contin">繼續</string>
</resources>
在 AndroidManifest.xml 中補上:
<!-- 請求網絡權限 --> <uses-permission android:name="android.permission.INTERNET"/>
少了這行,連線會直接拋出 UnknownHostException,而且是執行期才爆,編譯階段完全看不出來。
package com.dragon.android.textbar;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
/**
* 只有建立某個 View 的執行緒才能改變該 View 的 UI,主執行緒也稱 UI 執行緒
*/
public class MainActivity extends Activity {
private ProgressBar progressBar1;
private Button button1;
private TextView textView1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
progressBar1 = (ProgressBar) findViewById(R.id.progressBar1);
button1 = (Button) findViewById(R.id.button1);
textView1 = (TextView) findViewById(R.id.textView1);
}
public void startLoad(View view) {
String text = (String) button1.getText();
button1.setText(text.equals(getResources().getString(R.string.start))
? R.string.stop
: (text.equals(getResources().getString(R.string.stop))
? R.string.contin : R.string.stop));
progressBar1.setIndeterminate(false);
new Thread(new Runnable() {
private int percent;
@Override
public void run() {
try {
// 開啟 URL 必須在子執行緒
URL url = new URL(
"https://b.zol-img.com.cn/sjbizhi/images/9/540x960/1472549276394.jpg");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int contentLength = conn.getContentLength();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int len = -1;
int sum = 0;
while ((len = is.read(buffer)) != -1) {
sum += len;
// 注意轉型方式,否則整數除法會讓結果一直是 0
percent = (int) (100.0 * sum / contentLength);
// 切回主執行緒更新 UI
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar1.setProgress(percent);
textView1.setText(percent + "%");
if (percent == progressBar1.getMax()) {
Toast.makeText(MainActivity.this, "下載完成!",
Toast.LENGTH_SHORT).show();
}
}
});
}
is.close();
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
問題 1 與 2 其實是同一條規則的兩面:Android 網路請求不能跑在主執行緒(否則拋 NetworkOnMainThreadException),而 UI 更新又只能在建立該 View 的執行緒上進行。兩者合起來就決定了必然是「子執行緒下載 + runOnUiThread 更新進度」的結構。
percent 的計算要特別小心:寫成 100 * sum / contentLength 會因為整數除法永遠得到 0,必須先轉成浮點數(100.0 * sum)再整體轉回 int。
至於暫停與繼續(問題 4),這個版本還沒有實作。要做真正的斷點續傳,需要把已下載的位元組寫入本機檔案,記錄下載位置,重新開始時帶上 Range 請求標頭從中斷處續傳。這部分留待後續補充。
CoordinatorLayout 用法整理:Behavior 機制與自定義聯動效果
近幾年在 Android Studio 新建專案或 Module 時,會發現最外層布局不再是 LinearLayout 或 RelativeLayout,而是一個陌生的傢
修改 Android 4.4.3 聯絡人頭像,讓預設顯示中文首字
在 Android 4.4.3 上,聯絡人頭像預設會顯示姓名首字母,但卻不支援中文字元,如下圖所示:當聯絡人名字的第一位是英文字元(a-z 或 A-Z)時,預設頭像會顯示
ExpandableListView 分組列表完整實作教學
要做類似即時通訊軟體裡「分組/聯絡人」那種可展開的兩級列表,ExpandableListView 是最直接的選擇。下面用一個完整範例走一遍:實體設計、Adapter 覆寫
Android 開發基礎:Main 執行緒向 Worker 執行緒發送訊息
Android 中 UI 更新只能在主執行緒進行,而耗時工作要放在背景。兩者之間靠 Handler 與 Message 溝通。本文示範的是較少見但觀念上很關鍵的方向:由