Created
March 2, 2021 16:40
-
-
Save parthdesai1208/9cf6df2e8ba250cee2895ac057af4d57 to your computer and use it in GitHub Desktop.
Check internet across multiple OS version
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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