Reputation: 2176
As the old way of detecting wifi connection (getNetworkInfo) is deprecated in android, I am trying to migrate my app to the latest way, below is what I have for now (in Kotlin):
fun isWifiConnected(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
cm?.activeNetwork?.let { network ->
cm.getNetworkCapabilities(network)?.let { capability ->
return capability.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}
}
return false
}
It works well until I get vpn connected (on my samsung s8 + shadowsocks), the capability in above code no longer has TRANSPORT_WIFI transport, but TRANSPORT_VPN instead. And if I connect vpn without wifi then get wifi connected, isWifiConnected returns true again (capability has both TRANSPORT_WIFI and TRANSPORT_VPN in this case).
It seems that the previous transport capabilities would all be reset to false when vpn connection gets established, which sounds like a bug to me, why having one new capability needs to reset old capabilities?
I was hoping this is just a bug of my vpn app (shadowsocks) but I tested same cases on my pixel 2 + shadowsocks, which works quite fine, isWifiConnected returns true as long as wifi is connected, no matter having vpn or not.
So this is a Samsung bug?
Upvotes: 3
Views: 910
Reputation: 2176
The solution works well so far:
fun isWifiEnabled(context: Context): Boolean {
val wm = context.getSystemService(Context.WIFI_SERVICE) as WifiManager?
return wm?.isWifiEnabled ?: false
}
Upvotes: 1