2014-10-03 137 views
-1

如何检查我的应用程序是否连接到互联网?检查应用程序是否连接到互联网

我发现这篇文章,但似乎你只能检查连接是否可用。 Detect whether there is an Internet connection available on Android

这篇文章确实有正确的答案,我离我的wifi太远并且总是不能通过测试。问题已经解决了。

我想能够检查这样的事情:

if(!isConnectedToInternet()) 
{ 
    Toast.makeText(getApplicationContext(), "Please connect to the internet.", 
    Toast.LENGTH_LONG).show(); 
} 
+0

'isConnectedToInternet'是什么?一个方法或简单的变量 – Rustam 2014-10-03 04:28:32

回答

1

answer from the link you attached实际上做几乎你想要达到的目的是相同的。你只需要修改几行:

private boolean isConnectedToInternet() { 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetwork= connectivityManager.getActiveNetworkInfo(); 
    return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); 
} 

你可以从Android的

检查 documentation & guides
+0

我在想代码不工作,但实际上离我的wifi太远了。所以原来的答案是正确的,你也是。谢谢! – 2014-10-03 04:53:47

1

尝试检查这样的:

private boolean isConnectedToInternet() { 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnected(); 
} 

检查这里:

if(!isConnectedToInternet()) 
{ 
    Toast.makeText(getApplicationContext(), "Please connect to the internet.", 
    Toast.LENGTH_LONG).show(); 
} 
0

检查这个代码,对我来说工作很好

public boolean isConnectingToInternet() { 
    ConnectivityManager connectivity = (ConnectivityManager) _context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    if (connectivity != null) { 
     NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
     if (info != null) 
      for (int i = 0; i < info.length; i++) 
       if (info[i].getState() == NetworkInfo.State.CONNECTED) { 
        return true; 
       } 

    } 
    return false; 
} 

检查这样

boolean isInternetPresent = cd.isConnectingToInternet(); 
    if (isInternetPresent) { 


    } else { 

     Toast.makeText(getApplicationContext(), 
       getResources().getString(R.string.internet_error), 
       Toast.LENGTH_LONG).show(); 
    } 
+0

你是否在意解释? – 2014-10-03 04:28:55

0

你需要检查,有一个已建立的连接

private boolean isConnected() { 
ConnectivityManager cm 
     = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo(); 
return activeNetworkInfo != null && activeNetworkInfo.isConnected() && cm.requestRouteToHost(activeNetworkInfo.getType(), yourHostAddress); 
} 

,然后检查是否有路由到您想要的主机(您可以使用Google进行测试)。检查http://developer.android.com/reference/android/net/ConnectivityManager.html#requestRouteToHost(int,int)

希望它有帮助。