android runtime_error ai_generated true

android.os.NetworkOnMainThreadException

ID: android/networkonmainthreadexception

Also available as: JSON · Markdown · 中文
92%Fix Rate
88%Confidence
1Evidence
2023-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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/NetworkOnMainThreadException

Workarounds

  1. 95% success Use Kotlin Coroutines: wrap network call in viewModelScope.launch(Dispatchers.IO) { ... }
    Use Kotlin Coroutines: wrap network call in viewModelScope.launch(Dispatchers.IO) { ... }
  2. 90% success Use RxJava: subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
    Use RxJava: subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
  3. 80% success Use Thread: new Thread(() -> { /* network call */ runOnUiThread(() -> updateUI()); }).start()
    Use Thread: new Thread(() -> { /* network call */ runOnUiThread(() -> updateUI()); }).start()

中文步骤

  1. 使用 Kotlin 协程:在 viewModelScope.launch(Dispatchers.IO) { ... } 中包装网络调用
  2. 使用 RxJava:subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
  3. 使用 Thread:new Thread(() -> { /* 网络调用 */ runOnUiThread(() -> updateUI()); }).start()

Dead Ends

Common approaches that don't work:

  1. 70% fail

    This only allows cleartext HTTP, but does not move the network call off the main thread.

  2. 50% fail

    AsyncTask is deprecated and can still leak context or cause threading issues; not a modern solution.

  3. 90% fail

    This only suppresses the exception for debugging, not a production fix; network on main thread still blocks UI.