0

我目前正在使用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)
}
4

1 回答 1

1

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

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

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

于 2021-03-16T03:34:53.010 回答