android runtime_error ai_generated true

android.os.NetworkOnMainThreadException

ID: android/networkonmainthreadexception

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://developer.android.com/reference/android/os/NetworkOnMainThreadException

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 50% 失败

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

  3. 90% 失败

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