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

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

    This method gives you the option for a really fast method (for real time feedback) or a slower method (for one off checks that require reliability)

    public boolean isNetworkAvailable(bool SlowButMoreReliable) {
        bool Result = false; 
        try {
            if(SlowButMoreReliable){
                ConnectivityManager MyConnectivityManager = null;
                MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    
                NetworkInfo MyNetworkInfo = null;
                MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo();
    
                Result = MyNetworkInfo != null && MyNetworkInfo.isConnected();
    
            } else
            {
                Runtime runtime = Runtime.getRuntime();
                Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
    
                int i = ipProcess.waitFor();
    
                Result = i== 0;
    
            }
    
        } catch(Exception ex)
        {
            //Common.Exception(ex); //This method is one you should have that displays exceptions in your log
        }
        return Result;
    }
    

提交回复
热议问题