android
runtime_error
ai_generated
true
android.os.NetworkOnMainThreadException
ID: android/networkonmainthreadexception
92%Fix Rate
88%Confidence
1Evidence
2023-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Android 3.0+ | active | — | — | — |
| minSdkVersion 11+ | active | — | — | — |
Root Cause
Performing a network operation on the main UI thread, which is forbidden by Android's strict mode since Honeycomb.
generic中文
在主 UI 线程上执行网络操作,自 Honeycomb 起 Android 的严格模式禁止此行为。
Official Documentation
https://developer.android.com/reference/android/os/NetworkOnMainThreadExceptionWorkarounds
-
95% success Use Kotlin Coroutines: wrap network call in viewModelScope.launch(Dispatchers.IO) { ... }
Use Kotlin Coroutines: wrap network call in viewModelScope.launch(Dispatchers.IO) { ... } -
90% success Use RxJava: subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
Use RxJava: subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
-
80% success Use Thread: new Thread(() -> { /* network call */ runOnUiThread(() -> updateUI()); }).start()
Use Thread: new Thread(() -> { /* network call */ runOnUiThread(() -> updateUI()); }).start()
中文步骤
使用 Kotlin 协程:在 viewModelScope.launch(Dispatchers.IO) { ... } 中包装网络调用使用 RxJava:subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
使用 Thread:new Thread(() -> { /* 网络调用 */ runOnUiThread(() -> updateUI()); }).start()
Dead Ends
Common approaches that don't work:
-
70% fail
This only allows cleartext HTTP, but does not move the network call off the main thread.
-
50% fail
AsyncTask is deprecated and can still leak context or cause threading issues; not a modern solution.
-
90% fail
This only suppresses the exception for debugging, not a production fix; network on main thread still blocks UI.