2012-12-17 29 views
1

我有以下方法,這將檢查在設備的互聯網連接:檢測Android應用程序中的Internet連接?

public static boolean checkInternetConnection(Context context) { 
    ConnectivityManager connectivityManager = 
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    if (connectivityManager.getActiveNetworkInfo() != null 
      && connectivityManager.getActiveNetworkInfo().isAvailable() 
      && connectivityManager.getActiveNetworkInfo().isConnected()) { 
     return true; 
    } else { 
     return false; 
    } 

} 

但過了一段我發現後此方法僅用於網絡連接性檢查;如設備連接到路由器並且路由器處於開啓狀態,但沒有互聯網可用,則此方法返回true。

那麼如何知道有真實的互聯網呢?

回答

0

試試這個功能...

public static Boolean checknetwork(Context mContext) 
    { 

     NetworkInfo info = ((ConnectivityManager) mContext 
       .getSystemService(Context.CONNECTIVITY_SERVICE)) 
       .getActiveNetworkInfo(); 
     if (info == null || !info.isConnected()) 
     { 

      return false; 
     } 
     if (info.isRoaming()) 
     { 
      // here is the roaming option you can change it if you want to 
      // disable internet while roaming, just return false 
      return true; 
     } 

     return true; 

    } 
4

那麼,什麼是 '實際的互聯網'?在任何特定時間連接到Internet上任何可能的主機的能力?有點難以測試,不是嗎?嘗試連接到一個着名的服務器(谷歌,美國國家航空航天局,你的國家的頂級供應商主頁),如果它的工作,你可能有'真正的互聯網'。

+0

我會走得更遠一點,並說其最好檢查一下,如果你可以連接到一個專用的IP地址,如谷歌的靜態的,而不是依賴於DNS做查找。 –

+0

是的,但是如果DNS被破壞,整個事情並沒有多大用處,對吧?也許,除非你正在編寫一個DNS應用程序,否則可能是 –

+0

...... –

1

我看到你的唯一方法是試圖連接到像谷歌這樣的網站,如果你得到了結果,那麼你可以肯定它,否則沒有互聯網活動。

相關問題