Android 获取 Wifi 连接状态

Android Get Status of Wifi Connection

我目前正在使用NetworkRequestNetworkCallback方法(Google官方推荐)获取Wifi连接状态,部分有效。

我预计 onUnavailable() 会在以下时间被调用:close app -> turn off Wifi -> launch app,但是什么也没有发生:

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)
}

好的,我得到了解决方案:

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

演示:https://youtu.be/OHFrtXVW4x4