2015-02-05 32 views

回答

0

這是你如何能做到這

檢查網絡可用這樣

功能1

private boolean isNetworkAvailable() { 
    ConnectivityManager cm = 
     (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
    return netInfo != null && netInfo.isConnectedOrConnecting(); 
} 

之後,檢查這樣,如果互聯網可

功能2

public static boolean isInternetAccessible(Context context) { 
    if (isWifiAvailable()) { 
     try { 
      HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
      urlc.setRequestProperty("User-Agent", "Test"); 
      urlc.setRequestProperty("Connection", "close"); 
      urlc.setConnectTimeout(1500); 
      urlc.connect(); 
      return (urlc.getResponseCode() == 200); 
     } catch (IOException e) { 
      Log.e(LOG_TAG, "Couldn't check internet connection", e); 
     } 
     } else { 
      Log.d(LOG_TAG, "Internet not available!"); 
     } 
    return false; 
} 
  1. 如果功能1返回錯誤 - >未連接到網絡
  2. 如果函數返回1 true並且函數2返回false - >已連接但沒有intenet
  3. 如果兩個函數都返回true - >可以訪問Internet

注意您將需要這兩個權限在清單

<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
我測試了它
+0

和它的偉大工程,非常感謝Rohit5k2 – 2015-02-09 19:11:59

+0

很高興我能幫忙。 – Rohit5k2 2015-02-09 19:15:22

+0

你會如何處理異步任務?我希望布爾值返回到調用它的活動。 – TheLearner 2017-09-28 16:55:56

0

請驗證您是否被允許從您的APP訪問互聯網。

該權限在AndroidManifest.xml中定義。 請確保您有以下權限

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

代碼方法

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
StrictMode.setThreadPolicy(policy); 
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection()); 
urlc.setRequestProperty("User-Agent", "Test"); 
urlc.setRequestProperty("Connection", "close"); 
urlc.setConnectTimeout(1000); 
urlc.connect(); 
Log.i(Tag,Integer.toString(urlc.getResponseCode())); 
相關問題