You are able to check the current state of your internet access using the Connectivity Service
. Using that service, you can have a callback that will alert you when your internet access situation changes, here's a little example (in Kotlin):
val connectivityManager =
getApplication<Application>().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
super.onAvailable(network)
// Do something
}
override fun onLost(network: Network) {
super.onLost(network)
// Do something else
}
}
connectivityManager.registerNetworkCallback(
NetworkRequest.Builder().build(),
networkCallback
)
At the same time, you can also check for wifi using the Wifi Service
and data using the Telephony Service
. Here's an example where I check both to determine internet situation, though you are free to check for either individually if you see fit:
val wifiManager =
getApplication<Application>().applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val simManager =
getApplication<Application>().applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (wifiManager.connectionInfo.supplicantState != SupplicantState.COMPLETED && simManager.dataState != TelephonyManager.DATA_CONNECTED) {
// Do something
}
Keep in mind you will need to enable these permissions in the Android Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Using these services you can selectively disable the app or certain functionalities if the user has no internet.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…