2014-10-03 133 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)

希望它有幫助。