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

后端 未结 30 3333
猫巷女王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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:02

    Of everything I have seen so far shortest and cleanest way should be:

    public final static boolean isConnected( Context context )
    {   
       final ConnectivityManager connectivityManager = 
             (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );  
       final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();    
       return networkInfo != null && networkInfo.isConnected();
    }
    

    PS: This does not ping any host, it just checks the connectionstatus, so if your router has no internet connection and your device is connected to it this method would return true although you have no internet.
    For an actual test I would recommend execuding a HttpHead request (e.g. to www.google.com) and check the status, if its 200 OK everything is fine and your device has an internet connection.

提交回复
热议问题