Android 3.0+ (API 11+) 嚴禁主線程網絡 I/O,違反拋 NetworkOnMainThreadException。代碼在 Android 2.3 正常,ICS 後崩潰。解決:移至 AsyncTask、Thread 或現代網絡庫。
// 主線程直接請求
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect(); // API 11+ 拋異常
private class FetchChangelogTask extends AsyncTask {
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://example.com/changelog.txt");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) sb.append(line).append("\n");
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
showDialog(result); // UI 更新
}
}
}
// 調用
new FetchChangelogTask().execute();
withContext(Dispatchers.IO) 切換線程。嚴守主線程禁網規則,App 穩定流暢。