I got a AsyncTask
that is supposed to check the network access to a host name. But the doInBackground()
is never timed out. Anyone have a clue?
I have placed the function in a ViewModel
, which has the viewModelScope
. Using an observable LiveData
I inform an activity about the connection.
ViewModel
fun checkInternetConnection() {
viewModelScope.launch {
withContext(Dispatchers.IO) {
try {
val timeoutMs = 3000
val socket = Socket()
val socketAddress = InetSocketAddress("8.8.8.8", 53)
socket.connect(socketAddress, timeoutMs)
socket.close()
withContext(Dispatchers.Main) {
_connection.value = true
}
}
catch(ex: IOException) {
withContext(Main) {
_connection.value = false
}
}
}
}
}
private val _connection = MutableLiveData()
val connection: LiveData = _connection
Activity
private fun checkInternetConnection() {
viewModel.connection.observe(this) { hasInternet ->
if(!hasInternet) {
//hasn't connection
}
else {
//has connection
}
}
}