3

在我的应用程序中,我需要检查设备是否已连接到 Internet。我尝试使用 ConnectivityManager,但它没有给出 100% 的精确结果。例如,我可能有 Wi-Fi 连接,但仍然无法访问互联网资源。在我的情况下,我必须在通过 wi-fi 连接后打开一个 VPN 连接,才能真正访问 Internet。所以使用 ConnectivityManager 的方法不起作用。

那么,关于上述情况 - 我应该编写手动 http 请求以确保还是有其他方法?

这是我正在使用的一些代码

ConnectivityManager cm =  (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable();
4

5 回答 5

3

是的,你是对的,要检查你是否可以访问你需要明确测试的互联网。如果您需要 HTTP 访问,您可以尝试连接到您稍后想要连接的主机。

但是,您应该使用稍后打算使用的连接方法。HTTP 可以工作,但 FTP 不行。因此,如果您需要 FTP 访问,您应该对其进行测试。


如果您还想获取外部 IP,可以使用此方法:

public static InetAddress getExternalIp() throws IOException {
    URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Protocol", "Http/1.1");
    connection.addRequestProperty("Connection", "keep-alive");
    connection.addRequestProperty("Keep-Alive", "1000");
    connection.addRequestProperty("User-Agent", "Web-Agent");

    Scanner s = new Scanner(connection.getInputStream());
    try {
        return InetAddress.getByName(s.nextLine());
    } finally {
        s.close();
    }
}

如果您从该方法成功获取了 IP 地址,则可以通过 HTTP 连接到该地址。

于 2012-06-19T08:18:13.487 回答
2

ConnectionTimeout我认为设置为 HTTPRequest 是最好的方法,而不是每次都检查互联网连接,

try
  {

   HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   // Set the timeout in milliseconds until a connection is established.
   // The default value is zero, that means the timeout is not used. 
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   // Set the default socket timeout (SO_TIMEOUT) 
   // in milliseconds which is the timeout for waiting for data.
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
   // create object of DefaultHttpClient    
   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);
   // get response entity
   HttpEntity entity = response.getEntity();
   // convert entity response to string

     if (entity != null)
      {
         result = EntityUtils.toString(entity);
      }

   }
 catch (SocketException e)
  {
     return "-222" + e.toString();
  }
 catch (Exception e)
  {
     return "-333" + e.toString();
  }
于 2012-06-19T08:26:43.680 回答
0

试试这个,

     private boolean checkInternetConnection() {
     try {

            ConnectivityManager nInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            nInfo.getActiveNetworkInfo().isConnectedOrConnecting(); 

            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
                return true;
            } else { 
                return false; }

        } catch (Exception e) {
            return false;
        }
    }

它对我来说非常有用......

希望能帮助到你

于 2012-06-19T08:24:32.940 回答
0

试试这个,

NetworkInfo ActiveNetwork;
String Isconnected="";
ConnectivityManager connectivitymanager;
connectivitymanager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Connection con=new Connection();
try
{           
    ActiveNetwork=connectivitymanager.getActiveNetworkInfo();
    Isconnected="true";                 
}
catch(Exception error)
{
    IsConnected="false";
}
于 2012-06-19T08:25:42.333 回答
0

试试这个

private void MyCheckinternet() {
        // TODO Auto-generated method stub
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
                    connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                //we are connected to a network
                connected = true;
            }
            else
            {
                connected = false;
    }
}
于 2012-09-18T13:33:58.237 回答