Skip to content

Instantly share code, notes, and snippets.

@parthdesai1208
Created March 2, 2021 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parthdesai1208/9cf6df2e8ba250cee2895ac057af4d57 to your computer and use it in GitHub Desktop.
Save parthdesai1208/9cf6df2e8ba250cee2895ac057af4d57 to your computer and use it in GitHub Desktop.
Check internet across multiple OS version
fun Context?.isOnline(failBlock : () -> Unit = { globalIntenetFailBock() }, successBlock : () -> Unit ) {
this?.apply {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
val b : Boolean = false
if (cm == null) b = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
NetworkCapabilities cap = cm.getNetworkCapabilities(cm.getActiveNetwork())
if (cap == null) b = false
b = cap.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Network[] networks = cm.getAllNetworks()
for (Network n: networks) {
NetworkInfo nInfo = cm.getNetworkInfo(n)
if (nInfo != null && nInfo.isConnected()) b = true
}
} else {
NetworkInfo[] networks = cm.getAllNetworkInfo();
for (NetworkInfo nInfo: networks) {
if (nInfo != null && nInfo.isConnected()) b = true
}
}
b = false
if (b){
successBlock()
}else{
failBlock()
}
}?:failBlock()
}
fun Context?.globalIntenetFailBock(){
// no internet code here
}
use it like,
isOnline{
//yay internet... hurray...
},{
//no internet sorry!!!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment