android
runtime_error
ai_generated
true
android.os.NetworkOnMainThreadException
ID: android/networkonmainthreadexception
92%修复率
88%置信度
1证据数
2023-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Android 3.0+ | active | — | — | — |
| minSdkVersion 11+ | active | — | — | — |
根因分析
在主 UI 线程上执行网络操作,自 Honeycomb 起 Android 的严格模式禁止此行为。
English
Performing a network operation on the main UI thread, which is forbidden by Android's strict mode since Honeycomb.
官方文档
https://developer.android.com/reference/android/os/NetworkOnMainThreadException解决方案
-
使用 Kotlin 协程:在 viewModelScope.launch(Dispatchers.IO) { ... } 中包装网络调用 -
使用 RxJava:subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
-
使用 Thread:new Thread(() -> { /* 网络调用 */ runOnUiThread(() -> updateUI()); }).start()
无效尝试
常见但无效的做法:
-
70% 失败
This only allows cleartext HTTP, but does not move the network call off the main thread.
-
50% 失败
AsyncTask is deprecated and can still leak context or cause threading issues; not a modern solution.
-
90% 失败
This only suppresses the exception for debugging, not a production fix; network on main thread still blocks UI.