android.os.NetworkOnMainThreadException
Android 4.0+ (API 14+) 嚴禁主線程 (UI 線程) 執行網絡 I/O 操作。
new AsyncTask() {
protected String doInBackground(Void... params) {
return httpGet(url); // 子線程
}
protected void onPostExecute(String result) {
updateUI(result); // 主線程
}
}.execute();
new Thread(() -> {
String result = httpGet(url);
runOnUiThread(() -> updateUI(result));
}).start();
新項目直接使用 OkHttp + Coroutines (Kotlin) 或 Retrofit + RxJava,避免手動線程管理。