Incorrect connection state obtained through ConnectivityManager on Android 9

57 views Asked by At

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?

1

There are 1 answers

0
404NotFound On

You can use callback also like this to check whether wifi is connected or not:

private fun listenNetworkChanges(mContext: Context) {
        connectivityManager =
            mContext.getSystemService() as ConnectivityManager?
        val networkRequest =
            NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .build()
        networkCallback = object : NetworkCallback() {
            override fun onAvailable(network: Network) {
                Log.d(TAG, "listenNetworkChanges onAvailable $network")
            }

            override fun onLost(network: Network) {
                Log.d(TAG, "listenNetworkChanges onLost $network")
            }

            override fun onCapabilitiesChanged(
                network: Network,
                networkCapabilities: NetworkCapabilities
            ) {
                //do nothing
            }
        }
        connectivityManager?.registerNetworkCallback(networkRequest, networkCallback)
    }