Skip to content

Instantly share code, notes, and snippets.

@hissain
Created May 5, 2020 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hissain/3ed7d51521f61cd61671b47e8f99c4b9 to your computer and use it in GitHub Desktop.
Save hissain/3ed7d51521f61cd61671b47e8f99c4b9 to your computer and use it in GitHub Desktop.
object MyReachability {
private fun hasNetworkAvailable(context: Context): Boolean {
val service = Context.CONNECTIVITY_SERVICE
val manager = context.getSystemService(service) as ConnectivityManager?
val network = manager?.activeNetworkInfo
Log.d(classTag, "hasNetworkAvailable: ${(network != null)}")
return (network?.isConnected) ?: false
}
fun hasInternetConnected(context: Context): Boolean {
if (hasNetworkAvailable(context)) {
try {
val connection = URL(Constants.REACHABILITY_SERVER).openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Test")
connection.setRequestProperty("Connection", "close")
connection.connectTimeout = 1500 // configurable
connection.connect()
Log.d(classTag, "hasInternetConnected: ${(connection.responseCode == 200)}")
return (connection.responseCode == 200)
} catch (e: IOException) {
Log.e(classTag, "Error checking internet connection", e)
}
} else {
Log.w(classTag, "No network available!")
}
Log.d(classTag, "hasInternetConnected: false")
return false
}
fun hasServerConnected(context: Context): Boolean {
if (hasNetworkAvailable(context)) {
try {
val connection = URL(Constants.LANDING_SERVER).openConnection() as HttpURLConnection
connection.setRequestProperty("User-Agent", "Test")
connection.setRequestProperty("Connection", "close")
connection.connectTimeout = 1500 // configurable
connection.connect()
Log.d(classTag, "hasServerConnected: ${(connection.responseCode == 200)}")
return (connection.responseCode == 200)
} catch (e: IOException) {
Log.e(classTag, "Error checking internet connection", e)
}
} else {
Log.w(classTag, "Server is unavailable!")
}
Log.d(classTag, "hasServerConnected: false")
return false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment