Created
May 5, 2020 18:23
-
-
Save hissain/3ed7d51521f61cd61671b47e8f99c4b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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