I want to write a broadcast receiver that can get whether wifi is conneted. However, I always get wrong result. How to fix it?
class wifiStateReceiver: BroadcastReceiver() {
override fun onReceive(ctx: Context, intent: Intent) {
if(intent.action == WifiManager.NETWORK_STATE_CHANGED_ACTION){
Log.i("TEST", "Wifi Connection: ${isWifiNetworkAvailable(ctx)}")
}
}
private fun isWifiNetworkAvailable(context: Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(network) ?: return false
return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
return connectivityManager.activeNetworkInfo?.isConnected ?: false
}
}
}
It seems that only first execution of onReceive() after opening APP is correct. Then when Wifi is turned on but doesn't connect to anything, networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) still returns true: Wifi Connect: true
. When the phone connects to wifi, it returns false.
How can I get whether the phone is connected to WiFi correctly?
You can use callback also like this to check whether wifi is connected or not: