我目前正在使用NetworkRequest
和NetworkCallback
方法(由 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)
}