android
runtime_error
ai_generated
true
java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'void android.net.ConnectivityManager$NetworkCallback.onAvailable(android.net.Network)'
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.net.ConnectivityManager$NetworkCallback.onAvailable(android.net.Network)' on a null object reference
ID: android/connectivity-manager-network-callback-null
80%修复率
82%置信度
1证据数
2024-01-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| Android 10 (API 29) | active | — | — | — |
| Android 11 (API 30) | active | — | — | — |
| Android 12 (API 31) | active | — | — | — |
根因分析
当 ConnectivityManager 触发回调时 NetworkCallback 实例为 null,通常是由于过早取消注册或生命周期管理不当。
English
NetworkCallback instance is null when ConnectivityManager triggers the callback, often due to premature unregistration or lifecycle mismanagement.
官方文档
https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback解决方案
-
Check callback for null before unregistering: `if (networkCallback != null) { connectivityManager.unregisterNetworkCallback(networkCallback); }` -
Use a WeakReference to hold the callback: `private var callbackRef: WeakReference<NetworkCallback>? = null` and check `callbackRef?.get()` before use.
-
In Activity onStop(), set a flag and delay unregistration until onDestroy() with null check: `if (isCallbackRegistered && networkCallback != null) { ... }`
无效尝试
常见但无效的做法:
-
Wrap callback call in try-catch NullPointerException
90% 失败
Silently swallows the error but doesn't fix the root cause; callback may never fire again.
-
Register callback in Application.onCreate()
75% 失败
Application context may outlive Activity; callback still null if unregistered incorrectly.
-
Use HandlerThread for callback registration
85% 失败
Threading doesn't prevent null reference; the issue is lifecycle, not threading.