您必须将网络类型限制为Wifi。
1.构建NetworkRequest
:
val networkRequest = getNetworkRequest()
private fun getNetworkRequest(): NetworkRequest {
return NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) //here!!
.build()
}
2. 构建NetworkCallback
:
val networkCallback = getNetworkCallBack()
private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
return object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) { //when Wifi is on
super.onAvailable(network)
Toast.makeText(requireContext(), "Wifi is on!", Toast.LENGTH_SHORT).show()
}
override fun onLost(network: Network) { //when Wifi 【turns off】
super.onLost(network)
Toast.makeText(requireContext(), "Wifi turns off!", Toast.LENGTH_SHORT).show()
}
}
}
3.注册和注销:
fun getConnectivityManager() = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
override fun onResume() { //start monitoring when in the foreground
super.onResume()
getConnectivityManager().registerNetworkCallback(networkRequest, networkCallback)
}
override fun onPause() { //stop monitoring when not fully visible
super.onPause()
getConnectivityManager().unregisterNetworkCallback(networkCallback)
}
4.不要忘记许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
演示:https ://youtu.be/RPRcGbuB6eI