You have to restrict the network type to Wifi.
1. Build the NetworkRequest
:
val networkRequest = getNetworkRequest()
private fun getNetworkRequest(): NetworkRequest {
return NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) //here!!
.build()
}
2. Build the 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. Register and Unregister:
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. Don't forget the permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Demo: https://youtu.be/RPRcGbuB6eI
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…