How to check internet access on Android? InetAddress never times out

后端 未结 30 3358
猫巷女王i
猫巷女王i 2020-11-21 04:45

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?

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 04:57

    Kotlin and coroutines

    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
             }
         }
      }
    

提交回复
热议问题