2016-05-14 166 views
2

我看了這個回答關於獲得互聯網連接狀態在安卓Android的 - 檢查網絡連接

https://stackoverflow.com/a/22256277/4225644

但如果我有沒有接入Internet的網絡連接它不能正常工作,例如,此方法需要很長時間才能返回False:

public Boolean isOnline() { 
try { 
    Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com"); 
    int returnVal = p1.waitFor(); 
    boolean reachable = (returnVal==0); 
    return reachable; 
} catch (Exception e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
return false; 
} 

如何縮短該時間以獲得更快的答案?

回答

1

使用此代碼:

public static boolean isInternetConnected(Context context) { 
    ConnectivityManager cm = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 

    NetworkInfo ni = cm.getActiveNetworkInfo(); 

    if (ni == null) 
     return false; 
    else { 
     if (ni.isConnected()) 
      if (isOnline(context)) 
       return true; 
      else 
       return false; 
     return false; 
    } 
} 


public static boolean isOnline(Context context) { 
    ConnectivityManager cm = (ConnectivityManager) context 
      .getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnected()) { 
     try { 
      URL url = new URL("http://www.google.com"); 
      HttpURLConnection urlc = (HttpURLConnection) url 
        .openConnection(); 
      urlc.setConnectTimeout(2000); 
      urlc.connect(); 
      if (urlc.getResponseCode() == 200) { 
       return new Boolean(true); 
      } 
     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
    return false; 
} 
+0

這工作完美! 謝謝伊朗:) –

+0

坦克Alireza.pir :)。 –

0

你可以檢查是否有與

ConnectivityManager cm = 
     (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); 

NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
boolean isConnected = activeNetwork != null && 
         activeNetwork.isConnectedOrConnecting(); 

連接這是肯定的一個更快的方法,以確定是否有網絡存取權限,而不是執行請求,並等待故障。

另請參閱docs

+1

但這並不告訴你,如果你有互聯網接入或不 – waqaslam

+0

哦,我明白了。也許https://github.com/novoda/merlin是你正在尋找的。 – fiipi

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; 
} 

,並給予許可,您manifest.xml

<uses-permission android:name="android.permission.INTERNET" />