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

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

    It's works for me. Try it out.

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        try {
            URL url = new URL("http://stackoverflow.com/posts/11642475/edit" );
            //URL url = new URL("http://www.nofoundwebsite.com/" );
            executeReq(url);
            Toast.makeText(getApplicationContext(), "Webpage is available!", Toast.LENGTH_SHORT).show();
        }
        catch(Exception e) {
            Toast.makeText(getApplicationContext(), "oops! webpage is not available!", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void executeReq(URL urlObject) throws IOException
    {
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) urlObject.openConnection();
        conn.setReadTimeout(30000);//milliseconds
        conn.setConnectTimeout(3500);//milliseconds
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
    
        // Start connect
        conn.connect();
        InputStream response =conn.getInputStream();
        Log.d("Response:", response.toString());
    }}
    
    0 讨论(0)
  • 2020-11-21 04:46

    Best approach:

    public static boolean isOnline() {
        try {
        InetAddress.getByName("google.com").isReachable(3);
    
        return true;
        } catch (UnknownHostException e){
        return false;
        } catch (IOException e){
        return false;
        }
        }
    
    0 讨论(0)
  • 2020-11-21 04:47

    Very important to check if we have connectivity with isAvailable() and if is possible to establish a connection with isConnected()

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

    and you can derterminate the type of network active WiFi :

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

    or mobile Móvil :

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

    don´t forget the permissions:

        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
       <uses-permission android:name="android.permission.INTERNET" />
    
    0 讨论(0)
  • 2020-11-21 04:48

    It does works for me:

    To verify network availability:

    private Boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();}
    

    To verify internet access:

    public Boolean isOnline() {
        try {
            Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
            int returnVal = p1.waitFor();
            boolean reachable = (returnVal==0);
            return reachable;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    
    0 讨论(0)
  • 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:

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    in your android manifest.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题