I try to get the internet status from a WiFi network. So I can raise a notification when the device doesn't have an internet connection through WiFi.
So the way I found to do it now with a not deprecated method is by using ConnectinityManager.NetworkCallback
(https://developer.android.com/reference/android/net/ConnectivityManager.NetworkCallback)
I succeeded check when the WiFi is disconnected or connected by using .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
And I succeded check when a device doesn't have Internet data with .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
But what I want is a callback to detect if there is internet or not through the WiFi it's connected. So I tried to add both items above, but it seems it doesn't work that way. The test I made is connecting a device to a hotspot, then disable the data from the hotspot. But it doesn't trigger the callback.
Here is the code I used (thanks to ConnectivityManager.NetworkCallback() -> onAvailable(Network network) method is not triggered when device connects to a internal wifi network) that has a related issue:
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
private val networkCallback = getNetworkCallBack()
private fun getNetworkCallBack(): ConnectivityManager.NetworkCallback {
return object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
Toast.makeText(applicationContext, "Internet is on!", Toast.LENGTH_SHORT).show()
}
override fun onLost(network: Network) {
super.onLost(network)
Toast.makeText(applicationContext, "Internet turns off!", Toast.LENGTH_SHORT).show()
}
}
}
private fun getConnectivityManager() = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private fun getNetworkRequest(): NetworkRequest {
return NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI) // internet check works without this but need it for WiFi status
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
}
override fun onResume() {
super.onResume()
getConnectivityManager().registerNetworkCallback(getNetworkRequest(), networkCallback)
}
override fun onPause() {
super.onPause()
getConnectivityManager().unregisterNetworkCallback(networkCallback)
}
}