2013-07-18 70 views
12

我想寫一個在我的應用程序,將區分活動的Wifi連接和實際連接到互聯網的一部分。使用連接管理器查找是否有活動的Wifi連接非常簡單,但是每次嘗試測試連接到Wifi時是否可以連接到網站,但沒有互聯網連接時,我都會以無限循環結束。
我試圖平谷歌然而,這最終以同樣的方式:檢查有效的互聯網連接Android

Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com"); 
int returnVal = 5; 
try { 
    returnVal = p1.waitFor(); 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} 
boolean reachable = (returnVal==0); 
return reachable; 

我也試過這個代碼:

if (InetAddress.getByName("www.xy.com").isReachable(timeout)) 
{ } 
else 
{ } 

,但我不能讓isReachable工作。

+0

檢查出的問題https://stackoverflow.com/questions/4238921/detect-whether-there-is-an-internet-connection-available-on-android – nyulan

回答

10

我用這個:

public static void isNetworkAvailable(Context context){ 
    HttpGet httpGet = new HttpGet("http://www.google.com"); 
    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 = 3000; 
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
    // Set the default socket timeout (SO_TIMEOUT) 
    // in milliseconds which is the timeout for waiting for data. 
    int timeoutSocket = 5000; 
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); 
    try{ 
     Log.d(TAG, "Checking network connection..."); 
     httpClient.execute(httpGet); 
     Log.d(TAG, "Connection OK"); 
     return; 
    } 
    catch(ClientProtocolException e){ 
     e.printStackTrace(); 
    } 
    catch(IOException e){ 
     e.printStackTrace(); 
    } 

    Log.d(TAG, "Connection unavailable"); 
} 

,而是來自其他計算器的答案,但我不能找到它。

編輯:

最後我發現:https://stackoverflow.com/a/1565243/2198638

+0

如果我timeoutConnection = 2000和int timeoutSocket = 3000; –

2

查詢一個這樣的網站:

讓你的類中加入下面的方法類實現AsyncTaskCompleteListenere<Boolean>

@Override 
public void onTaskComplete(Boolean result) { 
    Toast.makeText(getApplicationContext(), "URL Exist:" + result, Toast.LENGTH_LONG).show(); 
    // continue your job 
} 

爲您的課程添加一個簡單的testConnection方法,以便在您要檢查您的課程時調用nectivity:

public void testConnection() { 
     URLExistAsyncTask task = new URLExistAsyncTask(this); 
     String URL = "http://www.google.com"; 
     task.execute(new String[]{URL}); 
    } 

最後的URLExistAsyncTask類進行連通性測試作爲異步(後臺)任務和回叫你onTaskComplete方法進行一次:

public class URLExistAsyncTask extends AsyncTask<String, Void, Boolean> { 
     AsyncTaskCompleteListenere<Boolean> callback; 

     public URLExistAsyncTask(AsyncTaskCompleteListenere<Boolean> callback) { 
      this.callback = callback; 
     } 

     protected Boolean doInBackground(String... params) { 
      int code = 0; 
      try { 
       URL u = new URL(params[0]); 
       HttpURLConnection huc = (HttpURLConnection) u.openConnection(); 
       huc.setRequestMethod("GET"); 
       huc.connect(); 
       code = huc.getResponseCode(); 
      } catch (IOException e) { 
       return false; 
      } catch (Exception e) { 
       return false; 
      } 

      return code == 200; 
     } 

     protected void onPostExecute(Boolean result){ 
       callback.onTaskComplete(result); 
     } 
    } 
23

它確實爲我的作品:

驗證網絡可用性:

private Boolean isNetworkAvailable() { 
    ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting(); 
} 

要驗證網絡連接:

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

使用ping方法警告!這對我測試過的大多數設備都很好,但在S4 Mini上它不會。 –

+0

它不適用於4.3設備... @ JohnSmith – Josh

3

要檢查機器人裝置具有一個活動連接,我使用低於此hasActiveInternetConnection()方法(1)嘗試檢測如果網絡是可用的和(2)然後連接到google.com以確定網絡是否處於活動狀態。

public static boolean hasActiveInternetConnection(Context context) { 
     if (isNetworkAvailable(context)) { 
      if (connectGoogle()) { 
       return true; 
      } else {//one more try 
       return connectGoogle(); 
      } 

     } 
else 
{ 
      log("No network available! (in hasActiveInternetConnection())"); 
      return false; 
     } 
    } 


    public static boolean isNetworkAvailable(Context ct) 
{ 
     ConnectivityManager connectivityManager = (ConnectivityManager)ct.getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
     return activeNetworkInfo != null; 
    } 


    public static boolean connectGoogle() { 
     try { 
      HttpURLConnection urlc = (HttpURLConnection)(new URL("http://www.google.com").openConnection()); 
      urlc.setRequestProperty("User-Agent", "Test"); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(10000); 
      urlc.connect(); 
      return (urlc.getResponseCode() == 200); 

     } catch (IOException e) { 
      log("IOException in connectGoogle())"); 
      return false; 
     } 
    } 
3

下面是一個使用AsynTask避開那裏的Android崩潰時您嘗試連接在主線程,並介紹了一個警報,沖洗和重複選項爲用戶的問題,一些現代的代碼。

class TestInternet extends AsyncTask<Void, Void, Boolean> { 
    @Override 
    protected Boolean doInBackground(Void... params) { 
     try { 
      URL url = new URL("http://www.google.com"); 
      HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); 
      urlc.setConnectTimeout(3000); 
      urlc.connect(); 
      if (urlc.getResponseCode() == 200) { 
       return true; 
      } 
     } catch (MalformedURLException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
      return false; 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return false; 
     } 
     return false; 
    } 

    @Override 
    protected void onPostExecute(Boolean result) { 
     if (!result) { // code if not connected 
      AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
      builder.setMessage("An internet connection is required."); 
      builder.setCancelable(false); 

      builder.setPositiveButton(
        "TRY AGAIN", 
        new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
          new TestInternet().execute(); 
         } 
        }); 


      AlertDialog alert11 = builder.create(); 
      alert11.show(); 
     } else { // code if connected 
      doMyStuff(); 
     } 
    } 
} 

...

new TestInternet().execute(); 
+0

這很好,但沒有互聯網接入的WiFi連接需要很長時間,是否有任何解決方法? –

-1

我沒有使用此方法。它爲我工作!對於想要獲得真正互聯網的人來說!

public boolean isOnline() { 
    try { 
     HttpURLConnection httpURLConnection = (HttpURLConnection)(new URL("http://www.google.com").openConnection()); 
     httpURLConnection.setRequestProperty("User-Agent", "Test"); 
     httpURLConnection.setRequestProperty("Connection", "close"); 
     httpURLConnection.setConnectTimeout(10000); 
     httpURLConnection.connect(); 
     return (httpURLConnection.getResponseCode() == 200); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 

每次都這樣做!只需使用一個接收器 和=>

httpURLConnection.getResponseCode() == 200 

這意味着互聯網連接!

+1

爲了改進這個答案,我會注意到'connect'不能從主線程調用,並且'setReadTimeout'也會很好。 – LordParsley