Skip to content

Instantly share code, notes, and snippets.

@addeeandra
Last active December 10, 2019 01:03
Show Gist options
  • Save addeeandra/13122a68b3ba1824431948364c7c7c6e to your computer and use it in GitHub Desktop.
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)
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)
}
}
}
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()
}
@addeeandra
Copy link
Author

This snippets are unused anymore. You can simply use mConnectivityManager.isDefaultNetworkActive to check internet connectivity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment