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

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

    No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

    public boolean isOnline() {
        ConnectivityManager cm =
            (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
        return cm.getActiveNetworkInfo() != null && 
           cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }
    

    You can also use requestRouteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

    You will also need:

    
    

    in your android manifest.

提交回复
热议问题