Last active
December 10, 2019 01:03
-
-
Save addeeandra/13122a68b3ba1824431948364c7c7c6e to your computer and use it in GitHub Desktop.
Connection Check on Android - Available in 3 state - Disconnected, Connected (no internet), Connected (with internet)
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
import android.content.Context | |
import android.net.ConnectivityManager | |
import java.net.InetAddress | |
import java.net.UnknownHostException | |
class ConnectionService(context: Context) { | |
companion object { | |
private var mInstance: ConnectionService? = null | |
@Synchronized | |
fun instance(context: Context): ConnectionService { | |
if (mInstance == null) { | |
mInstance = ConnectionService(context) | |
} | |
return mInstance as ConnectionService | |
} | |
} | |
private val mConnectivityManager = | |
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager | |
fun getConnectionState(hostname: String = "google.com"): ConnectionState { | |
val activeNetInfo = mConnectivityManager.activeNetworkInfo | |
if (activeNetInfo != null && activeNetInfo.isConnected) { | |
val wifiConnected = ConnectionState.WifiConnected(activeNetInfo) | |
try { | |
val ipAddr = InetAddress.getByName(hostname) | |
if (!ipAddr.equals("")) { | |
return ConnectionState.InternetConnected(wifiConnected) | |
} | |
return ConnectionState.InternetDisconnected(wifiConnected) | |
} catch (e: UnknownHostException) { | |
return ConnectionState.InternetDisconnected(wifiConnected) | |
} | |
} else { | |
return ConnectionState.WifiDisconnected(activeNetInfo) | |
} | |
} | |
} |
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
import android.net.NetworkInfo | |
sealed class ConnectionState { | |
data class WifiConnected(val activeNetworkInfo: NetworkInfo) : ConnectionState() | |
data class WifiDisconnected(val activeNetworkInfo: NetworkInfo) : ConnectionState() | |
data class InternetConnected(val wifiConnected: WifiConnected) : ConnectionState() | |
data class InternetDisconnected(val wifiConnected: WifiConnected) : ConnectionState() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This snippets are unused anymore. You can simply use
mConnectivityManager.isDefaultNetworkActive
to check internet connectivity