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

后端 未结 30 3337
猫巷女王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:53

    You can iterate over all network connections and chek whether there is at least one available connection:

    public boolean isConnected() {
        boolean connected = false;
    
        ConnectivityManager cm = 
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    
            for (NetworkInfo ni : netInfo) {
                if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                        || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                        && ni.isConnected() && ni.isAvailable()) {
                    connected = true;
                }
    
            }
        }
    
        return connected;
    }
    
    0 讨论(0)
  • 2020-11-21 04:53

    You can use this method to detect network availability-

    public static boolean isDeviceOnline(Context context) {
            boolean isConnectionAvail = false;
            try {
                ConnectivityManager cm = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                return netInfo.isConnected();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return isConnectionAvail;
        }
    
    0 讨论(0)
  • 2020-11-21 04:54

    To get getActiveNetworkInfo() to work you need to add the following to the manifest.

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
    0 讨论(0)
  • 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<Boolean>()
     val connection: LiveData<Boolean> = _connection
    

    Activity

     private fun checkInternetConnection() {
         viewModel.connection.observe(this) { hasInternet ->
             if(!hasInternet) {
                 //hasn't connection
             }
             else {
                //has connection
             }
         }
      }
    
    0 讨论(0)
  • 2020-11-21 04:57

    This is covered in android docs http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

    0 讨论(0)
  • 2020-11-21 04:58
    public class Network {
    
    Context context;
    
    public Network(Context context){
        this.context = context;
    }
    
    public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null &&
                              activeNetwork.isConnectedOrConnecting();
    }
    
    }
    
    0 讨论(0)
提交回复
热议问题