編輯:關於 Android 程式設計
這一篇把幾個繞不開的基礎知識串起來:用 HttpURLConnection 抓網路資料、為什麼不能在主線程連網、Handler 消息機制怎麼用、以及在此之上延伸出的圖片查看器、新聞客戶端與 GET/POST 登入。後半段還有動畫與自定義控制項,留待下篇。
目標很單純:在 EditText 輸入網址,點擊按鈕抓取網頁源碼,顯示到 TextView 上。順帶一提,桌面版 IE 用 Shift+F12 可以叫出 HTTP Watch,用來觀察請求細節,除錯時很方便。

核心 API 是 HttpURLConnection,負責送出與接收資料。既然是網路請求,權限必須先補上:
<uses-permission android:name="android.permission.INTERNET" />
請求流程:開子線程 → 讀取輸入框網址 → 建立 URL → 開連線 → 設定請求方式與逾時 → 檢查狀態碼 → 讀取輸入流 → 轉成字串 → 更新介面。
new Thread() {
@Override
public void run() {
try {
String path = et_path.getText().toString().trim();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 請求方式固定大寫
conn.setConnectTimeout(5000); // 逾時 5 秒
int code = conn.getResponseCode();
if (code == 200) { // 200 代表資源取得成功
InputStream in = conn.getInputStream();
String content = StreamTools.readStream(in);
tv_result.setText(content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
把輸入流轉字串的工具方法,用 1KB 緩衝區迴圈讀取,寫進 ByteArrayOutputStream 是最直白的做法:
public static String readStream(InputStream in) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = -1;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
in.close();
return new String(baos.toByteArray());
}
運行結果:

ScrollView 提供垂直滾動能力,但它只能包裹一個直接子佈局。要放多個元件,請先套一層 LinearLayout 之類的容器再放進去。

ANR 是 Application Not Responding 的縮寫,指的是主線程(UI 線程)被卡住而無法回應。常見誘因有三類:在主線程做網路連線、搬運大量資料、直接呼叫 Thread.sleep()。解法很樸素——把耗時工作丟到子線程。
從 Android 4.0 起,系統硬性禁止在主線程連網,否則拋出:
android.os.NetworkOnMainThreadException
另一條鐵律是:只有建立 View Hierarchy 的那條線程才能操作它。子線程更新 UI 會得到:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
要跨線程更新介面,就得靠消息機制——也就是 Handler。
四個步驟:在主線程建立 Handler、覆寫 handleMessage()、在子線程用這個 Handler 送訊息、在 handleMessage() 裡更新 UI。
private Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) { // what 是開發者自定的消息碼
case REQUEST_SUCCESS:
String content = (String) msg.obj; // obj 攜帶實際資料
tv_result.setText(content);
break;
case REQUEST_NOT_FOUND:
Toast.makeText(getApplicationContext(), "請求資源不存在", 0).show();
break;
case REQUEST_EXCEPTION:
Toast.makeText(getApplicationContext(), "伺服器忙碌,請稍後再試", 1).show();
break;
default:
break;
}
}
};
子線程送訊息:
new Thread() {
@Override
public void run() {
Message msg = new Message();
msg.what = REQUEST_SUCCESS;
msg.obj = content;
handler.sendMessage(msg); // 送出後 handleMessage 隨即被回呼
}
}.start();

Message:線程之間傳遞的信件。內建 what 欄位放消息碼,arg1/arg2 放整數,obj 放任意 Object,可以攜帶少量資料在兩側交換。
Handler:處理者。用 sendMessage() 把訊息投進佇列,訊息輾轉一圈後,最終回到它自己的 handleMessage()。因為 Handler 建立在哪條線程,回呼就在哪條線程執行,這正是更新 UI 的關鍵。
MessageQueue:單向先進先出的消息佇列,每條線程只有一個,由 Looper 管理。訊息按時間排序排隊,等待被取出。
Looper:消息的搬運工。透過 Looper.loop() 進入無限迴圈,不斷從 MessageQueue 取出訊息,交給對應的 Handler 分發到 handleMessage()。主線程的 Looper 由系統建立,子線程若要用則需自行 Looper.prepare() 與 Looper.loop()。
串起來就是:Handler 把 Message 放進 MessageQueue,Looper 取出並分派回 Handler 處理。
輸入圖片網址,抓取網路資料並轉成 Bitmap,顯示到下方 ImageView。步驟是:發請求 → 把流轉成 Bitmap(BitmapFactory.decodeStream())→ 加網路權限 → 記得做快取。

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bitmap bitmap = (Bitmap) msg.obj;
iv_img.setImageBitmap(bitmap);
}
};
public void click(View v) {
new Thread() {
@Override
public void run() {
String path = et_path.getText().toString().trim();
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(in);
// Message.obtain() 會優先複用消息池中的物件
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
兩者都位於應用程式套件名稱目錄之下。

// 寫入 cache 目錄
public void click1(View v) {
try {
File file = new File(getCacheDir(), "info.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write("hello".getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// 寫入 files 目錄
public void click2(View v) {
try {
FileOutputStream fos = openFileOutput("info.txt", 0);
fos.write("hello".getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
差別在生命週期:使用者於應用程式管理介面點「清除快取」,cache 會被清空而 files 保留;點「清除資料」,兩者都會消失。實務結論:可重新抓取的暫存資料放 cache,不能重來的重要資料放 files。
顧名思義,就是把 Runnable 丟到 UI 線程執行。
new Thread() {
@Override
public void run() {
tv.setText("我更新了 UI"); // 短時間內不會報錯
}
}.start();
有趣的地方是:上面這段在子線程直接改 UI 往往不會立刻出錯,但只要加上 Thread.sleep(100) 阻塞超過系統審計閾值,就會拋出 CalledFromWrongThreadException。也就是說,真正的限制來自系統底層的看門狗機制,而非語法層面。
因此:單純更新介面用 runOnUiThread 就夠;需要跨線程傳遞參數、需要延遲或分發多種消息,就該用 Handler。
runOnUiThread(new Runnable() {
@Override
public void run() {
iv.setImageBitmap(cacheBitmap);
}
});
postDelayed():延遲執行,最典型的應用是 Splash 頁停留三秒後跳轉主頁。
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
tv.setText("3 秒後執行");
}
}, 3000);
需要週期性重複,可以搭配 Timer:
private Timer timer;
private TimerTask task;
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv.setText("每秒更新");
}
});
}
};
// 參數:任務物件、延遲多久開始、間隔多久執行一次
timer.schedule(task, 3000, 1000);
取消排程:
timer.cancel(); task.cancel();

Tomcat 目錄下放一個 news.xml 作為資料來源。

兩個容易踩到的坑:Tomcat 啟動畫面一閃而過,通常要檢查 JAVA_HOME 是否設定;XML 裡的圖片位址必須寫電腦的實際 IP,不能寫 localhost,因為手機上的 localhost 指的是手機自己。
主介面就是一個 ListView:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lv"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
子項佈局則是「左圖 + 標題 + 描述 + 類型標籤」的組合:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp">
<ImageView
android:id="@+id/iv_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:layout_toRightOf="@id/iv_icon"
android:ellipsize="end"
android:singleLine="true"
android:textColor="#000000"
android:textSize="22sp" />
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/tv_title"
android:layout_marginTop="3dp"
android:layout_toRightOf="@id/iv_icon"
android:ellipsize="end"
android:maxLines="2"
android:textColor="#9e9e9e"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/iv_icon"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:textColor="#ff0000"
android:textSize="16sp" />
</RelativeLayout>
先定義實體類 News,再從服務器抓 XML 並解析成集合。
public class News {
private String title;
private String description;
private String image;
private String type;
private String comment;
// 省略 getter / setter
}
private void initListData() {
new Thread() {
@Override
public void run() {
try {
String path = "https://192.168.11.86:8080/news.xml";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
InputStream in = conn.getInputStream();
newsLists = XmlParserUtils.parserXml(in);
runOnUiThread(new Runnable() {
@Override
public void run() {
// setAdapter 必須在主線程執行
lv.setAdapter(new MyAdapter());
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
用 XmlPullParser 逐節點解析,遇到 channel 節點建立集合,遇到 item 建立物件,遇到欄位節點取值,遇到 item 結束標籤就收進集合:
public static List<News> parserXml(InputStream in) throws Exception {
List<News> newsLists = null;
News news = null;
XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, "utf-8");
int type = parser.getEventType();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("channel".equals(parser.getName())) {
newsLists = new ArrayList<News>();
} else if ("item".equals(parser.getName())) {
news = new News();
} else if ("title".equals(parser.getName())) {
news.setTitle(parser.nextText());
} else if ("description".equals(parser.getName())) {
news.setDescription(parser.nextText());
} else if ("image".equals(parser.getName())) {
news.setImage(parser.nextText());
} else if ("type".equals(parser.getName())) {
news.setType(parser.nextText());
} else if ("comment".equals(parser.getName())) {
news.setComment(parser.nextText());
}
break;
case XmlPullParser.END_TAG:
if ("item".equals(parser.getName())) {
newsLists.add(news);
}
break;
}
type = parser.next();
}
return newsLists;
}
繼承 BaseAdapter,在 getView() 中做 convertView 複用,並依 type 決定標籤文案。
private class MyAdapter extends BaseAdapter {
@Override public int getCount() { return newsLists.size(); }
@Override public Object getItem(int position) { return newsLists.get(position); }
@Override public long getItemId(int position) { return position; }
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = View.inflate(getApplicationContext(), R.layout.item, null);
} else {
view = convertView;
}
SmartImageView iv_icon = view.findViewById(R.id.iv_icon);
TextView tv_title = view.findViewById(R.id.tv_title);
TextView tv_desc = view.findViewById(R.id.tv_desc);
TextView tv_type = view.findViewById(R.id.tv_type);
News news = newsLists.get(position);
iv_icon.setImageUrl(news.getImage(), R.drawable.bg);
tv_title.setText(news.getTitle());
tv_desc.setText(news.getDescription());
switch (Integer.parseInt(news.getType())) {
case 1: tv_type.setText(news.getComment() + "國內"); break;
case 2: tv_type.setText("跟帖"); break;
case 3: tv_type.setText("國外"); break;
default: break;
}
return view;
}
}
運行效果:

把 com 套件與原始碼複製進工程,然後在佈局中用「完整套件名 + 類名」宣告即可。

<com.loopj.android.image.SmartImageView
android:id="@+id/iv_icon"
android:layout_width="70dp"
android:layout_height="70dp"
android:src="@drawable/ic_launcher" />
原理不複雜:繼承 ImageView,在子線程抓圖並轉成 Bitmap,再用 Handler 送回主線程顯示。額外多做一件事——請求失敗或發生異常時,顯示預設的佔位圖。
public class MySmartImageView extends ImageView {
private Handler handler = new Handler() {
@Override
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1: // 成功:顯示網路圖片
MySmartImageView.this.setImageBitmap((Bitmap) msg.obj);
break;
case 2: // 狀態碼非 200:顯示佔位圖
case 3: // 發生異常:顯示佔位圖
MySmartImageView.this.setBackgroundResource((Integer) msg.obj);
break;
default:
break;
}
}
};
public MySmartImageView(Context context) { super(context); }
public MySmartImageView(Context context, AttributeSet attrs) { super(context, attrs); }
public MySmartImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setImageUrl(final String path) {
new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void setImageUrl(final String path, final int resource) {
new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream());
Message msg = Message.obtain();
msg.what = 1;
msg.obj = bitmap;
handler.sendMessage(msg);
} else {
Message msg = Message.obtain();
msg.what = 2;
msg.obj = resource;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
Message msg = Message.obtain();
msg.what = 3;
msg.obj = resource;
handler.sendMessage(msg);
}
}
}.start();
}
}

兩者的主要差異:GET 把參數拼在網址後面,POST 透過請求體傳送;POST 會多出 Content-Type 與 Content-Length 兩個請求標頭;GET 的資料量受限(舊 IE 約 1KB,其他瀏覽器約 4KB),POST 則寬鬆得多。因此含密碼的登入,用 POST 才是正確做法。
GET 版本:
public void click1(View v) {
final String name = et_username.getText().toString().trim();
final String pwd = et_password.getText().toString().trim();
new Thread() {
@Override
public void run() {
try {
String path = "https://192.168.19.89:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if (conn.getResponseCode() == 200) {
String content = StreamTools.readStream(conn.getInputStream());
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void showToast(final String content) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), content, 1).show();
}
});
}
POST 版本:
public void click2(View v) {
final String name = et_username.getText().toString().trim();
final String pwd = et_password.getText().toString().trim();
new Thread() {
@Override
public void run() {
try {
String path = "https://192.168.19.89:8080/web/LoginServlet";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
String data = "username=" + name + "&password=" + pwd;
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.getBytes().length + "");
conn.setDoOutput(true); // 允許向服務器寫入資料
conn.getOutputStream().write(data.getBytes());
if (conn.getResponseCode() == 200) {
String content = StreamTools.readStream(conn.getInputStream());
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
小提醒:Content-Length 應該用位元組數而非字元數,中文參數若用 data.length() 會算少,這是常見的取捨錯誤。上篇到這裡,下篇接著談點餐界面的幕布上升動畫。
Android 下拉刷新控制元件終結者:PullToRefreshLayout
PullToRefreshLayout 下拉刷新控制元件 下拉刷新是 Android 常見互動,但不同列表元件若各自實作,維護成本很高。PullToRefreshLayo
Android RatingBar 評分條詳解與自定義
一、概述與應用場景 RatingBar(評分條)是 SeekBar 與 ProgressBar 的擴展,它以星形圖標來直觀地表現評分等級。RatingBar 提供兩種使用
Android 如何獲取正在運行的應用程式並管理
想製作一個類似「清理加速」的小工具嗎?關鍵的第一步就是取得手機上正在運行的應用程式列表。本文以一個實際範例,示範如何透過 ActivityManager 讀取執行中的程式
Android 自定義 CircleImageView:一步做出圓形頭像與彩色邊框
圓形頭像幾乎是每個 App 的標配。雖然現在有 Glide 的 CircleCrop、CardView 等現成方案,但自己實作一遍,能徹底理解 BitmapShader