Android Get Status of Wifi Connection

732 Views Asked by At

I'm currently using NetworkRequest and NetworkCallback approach (recommended by Google official) to get status of Wifi connection, and it works partially.

I'm expecting the onUnavailable() will get called when: close app -> turn off Wifi -> launch app, however there is nothing happened:

private fun getNetworkRequest(): NetworkRequest {
    return NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)    //restric to Wifi type only
        .build()
}

private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
    return object : ConnectivityManager.NetworkCallback() {
        override fun onAvailable(network: Network) {            //works
            super.onAvailable(network)

            Toast.makeText(requireContext(), "Wifi is on!", Toast.LENGTH_SHORT).show()
        }

        override fun onLost(network: Network) {                 //works
            super.onLost(network)

            Toast.makeText(requireContext(), "Wifi turns off!", Toast.LENGTH_SHORT).show()
        }

        override fun onUnavailable() {                          //not works as expected
            super.onUnavailable()

            Toast.makeText(requireContext(), "Wifi unavailable!", Toast.LENGTH_SHORT).show()
        }
    }
}

fun Fragment.getConnectivityManager() = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

override fun onResume() {
    super.onResume()

    getConnectivityManager().registerNetworkCallback(networkRequest, networkCallback)
}
1

There are 1 best solutions below

0
On BEST ANSWER

Ok, I got the solution:

val isWifiOn = with(getConnectivityManager()) {
    getNetworkCapabilities(activeNetwork)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
}

Demo: https://youtu.be/OHFrtXVW4x4