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

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

    Take a look at the ConnectivityManager class. You can use this class to get information on the active connections on a host. http://developer.android.com/reference/android/net/ConnectivityManager.html

    EDIT: You can use

    Context.getSystemService(Context.CONNECTIVITY_SERVICE)
        .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) 
    

    or

    Context.getSystemService(Context.CONNECTIVITY_SERVICE)
        .getNetworkInfo(ConnectivityManager.TYPE_WIFI) 
    

    and parse the DetailedState enum of the returned NetworkInfo object

    EDIT EDIT: To find out whether you can access a host, you can use

    Context.getSystemService(Context.CONNECTIVITY_SERVICE)
        .requestRouteToHost(TYPE_WIFI, int hostAddress)
    

    Obviously, I'm using Context.getSystemService(Context.CONNECTIVITY_SERVICE) as a proxy to say

    ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE);
    cm.yourMethodCallHere();
    

提交回复
热议问题