Skip to content

Instantly share code, notes, and snippets.

@an01f01
Last active February 3, 2021 21:06
Show Gist options
  • Save an01f01/a43cdf845b8acf8200ac44c5114075b0 to your computer and use it in GitHub Desktop.
Save an01f01/a43cdf845b8acf8200ac44c5114075b0 to your computer and use it in GitHub Desktop.
fun isOnline(context: Context): Boolean {
val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val n = cm.activeNetwork
if (n != null) {
val nc = cm.getNetworkCapabilities(n)
//It will check for both wifi and cellular network
return nc!!.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) || nc.hasTransport(
NetworkCapabilities.TRANSPORT_WIFI)
}
return false
} else {
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnectedOrConnecting
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment