diff --git a/check_internet/src/main/java/xyz/teamgravity/checkinternet/CheckInternet.kt b/check_internet/src/main/java/xyz/teamgravity/checkinternet/CheckInternet.kt index e4524f0..c9f6ecf 100644 --- a/check_internet/src/main/java/xyz/teamgravity/checkinternet/CheckInternet.kt +++ b/check_internet/src/main/java/xyz/teamgravity/checkinternet/CheckInternet.kt @@ -7,14 +7,22 @@ import kotlinx.coroutines.withContext import java.io.IOException import java.net.InetSocketAddress import java.net.Socket +import kotlin.coroutines.resume +import kotlin.coroutines.suspendCoroutine class CheckInternet { + companion object { + private const val HOST_NAME = "8.8.8.8" + private const val PORT = 53 + private const val TIMEOUT = 1_500 + } + fun check(listener: (connected: Boolean) -> Unit) { CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) { try { val socket = Socket() - socket.connect(InetSocketAddress("8.8.8.8", 53), 1500) + socket.connect(InetSocketAddress(HOST_NAME, PORT), TIMEOUT) socket.close() withContext(Dispatchers.Main) { listener(true) @@ -26,4 +34,19 @@ class CheckInternet { } } } + + suspend fun check(): Boolean { + return suspendCoroutine { continuation -> + CoroutineScope(Dispatchers.IO).launch(Dispatchers.IO) { + try { + val socket = Socket() + socket.connect(InetSocketAddress(HOST_NAME, PORT), TIMEOUT) + socket.close() + continuation.resume(true) + } catch (e: IOException) { + continuation.resume(false) + } + } + } + } } \ No newline at end of file