检测Android设备是否具有Internet连接

我需要告诉我的设备是否有Internet连接。 我发现了很多答案:

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

(从检测Android上是否有可用的Internet连接 )

但是,这是不正确的,例如,如果我连接到无法访问Internet的无线网络 ,此方法将返回true … 有办法告诉设备是否有Internet连接,而不是只有连接什么东西?

你是对的。 您提供的代码仅检查是否有网络连接。 检查是否有活动的Internet连接的最佳方法是尝试通过http连接到已知的服务器。

 public static boolean hasActiveInternetConnection(Context context) { if (isNetworkAvailable(context)) { 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, "Error checking internet connection", e); } } else { Log.d(LOG_TAG, "No network available!"); } return false; } 

当然,您可以使用http://www.google.com URL来代替要连接的任何其他服务器,也可以使用您认识的服务器运行正常的服务器。

正如Tony Cho在下面的评论中指出的,确保你不要在主线程上运行这个代码,否则你会得到一个NetworkOnMainThread异常(在Android 3.0或更高版本中)。 改用AsyncTask或Runnable。

如果你想使用google.com,你应该看看Jeshurun的修改。 在他的回答中,他修改了我的代码,使它更高效一些。 如果你连接到

 HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204") .openConnection()); 

然后检查204的响应码

 return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0); 

那么你不必首先获取整个谷歌主页。

我稍微修改了THelper的答案,使用Android已经使用的已知黑客检查连接的WiFi网络是否具有Internet访问权限。 这比抓取整个Google主页更有效率。 看到这里和这里的更多信息。

 public static boolean hasInternetAccess(Context context) { if (isNetworkAvailable(context)) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204") .openConnection()); urlc.setRequestProperty("User-Agent", "Android"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1500); urlc.connect(); return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0); } catch (IOException e) { Log.e(TAG, "Error checking internet connection", e); } } else { Log.d(TAG, "No network available!"); } return false; } 
 public boolean isInternetWorking() { boolean success = false; try { URL url = new URL("https://google.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(10000); connection.connect(); success = connection.getResponseCode() == 200; } catch (IOException e) { e.printStackTrace(); } return success; } 

如果互联网真的可用,则返回true

确保你有这两个权限

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

如果你的目标棒棒糖或更高,可以使用新的NetworkCapabilities类,即:

 public static boolean hasInternetConnection(final Context context) { final ConnectivityManager connectivityManager = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); final Network network = connectivityManager.getActiveNetwork(); final NetworkCapabilities capabilities = connectivityManager .getNetworkCapabilities(network); return capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED); } 

试试这个

 public class ConnectionDetector { private Context _context; public ConnectionDetector(Context context) { this._context = context; } public boolean isConnectingToInternet() { if (networkConnectivity()) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL( "http://www.google.com").openConnection()); urlc.setRequestProperty("User-Agent", "Test"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(3000); urlc.setReadTimeout(4000); urlc.connect(); // networkcode2 = urlc.getResponseCode(); return (urlc.getResponseCode() == 200); } catch (IOException e) { return (false); } } else return false; } private boolean networkConnectivity() { ConnectivityManager cm = (ConnectivityManager) _context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; } } 

您必须将以下权限添加到清单文件中:

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

然后像这样打电话:

 if((new ConnectionDetector(MyService.this)).isConnectingToInternet()){ Log.d("internet status","Internet Access"); }else{ Log.d("internet status","no Internet Access"); } 

您不一定需要进行完整的HTTP连接。 你可以尝试打开TCP连接到一个已知的主机,如果成功,你有互联网连接。

 public boolean hostAvailable(String host, int port) { try (Socket socket = new Socket()) { socket.connect(new InetSocketAddress(host, port), 2000); return true; } catch (IOException e) { // Either we have a timeout or unreachable host or failed DNS lookup System.out.println(e); return false; } } 

然后只需检查:

 boolean online = hostAvailable("www.google.com", 80); 

基于接受的答案,我已经建立了这个类与一个监听器,所以你可以在主线程中使用它:

首先 :在后台检查互联网连接的InterntCheck类,然后调用一个监听器方法和结果。

 public class InternetCheck extends AsyncTask<Void, Void, Void> { private Activity activity; private InternetCheckListener listener; public InternetCheck(Activity x){ activity= x; } @Override protected Void doInBackground(Void... params) { boolean b = hasInternetAccess(); listener.onComplete(b); return null; } public void isInternetConnectionAvailable(InternetCheckListener x){ listener=x; execute(); } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null; } private boolean hasInternetAccess() { if (isNetworkAvailable()) { try { HttpURLConnection urlc = (HttpURLConnection) (new URL("http://clients3.google.com/generate_204").openConnection()); urlc.setRequestProperty("User-Agent", "Android"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(1500); urlc.connect(); return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0); } catch (IOException e) { e.printStackTrace(); } } else { Log.d("TAG", "No network available!"); } return false; } public interface InternetCheckListener{ void onComplete(boolean connected); } } 

其次 :在主线程中实例化类的一个实例,并等待响应(如果你已经在android中使用过Firebase api,那么在这之前你应该很熟悉!)。

 new InternetCheck(activity).isInternetConnectionAvailable(new InternetCheck.InternetCheckListener() { @Override public void onComplete(boolean connected) { //proceed! } }); 

现在在onComplete方法,你会得到设备是否连接到互联网。

 private static NetworkUtil mInstance; private volatile boolean mIsOnline; private NetworkUtil() { ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); exec.scheduleAtFixedRate(new Runnable() { @Override public void run() { boolean reachable = false; try { Process process = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com"); int returnVal = process.waitFor(); reachable = (returnVal==0); } catch (Exception e) { e.printStackTrace(); } mIsOnline = reachable; } }, 0, 5, TimeUnit.SECONDS); } public static NetworkUtil getInstance() { if (mInstance == null) { synchronized (NetworkUtil.class) { if (mInstance == null) { mInstance = new NetworkUtil(); } } } return mInstance; } public boolean isOnline() { return mIsOnline; } 

希望上面的代码可以帮助你,也确保你有我们的应用程序的互联网许可。