我正在开发一个应用程序,我想访问是否有互联网连接。 我可以使用访问网络状态
private Boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }但这只是返回手机是否连接到互联网。 我想知道连接后是否有互联网可用性。 比如,可能是服务器已关闭或互联网不可用。 请让我知道如何做到这一点!
I am developing an application where i want to access whether there is internet connectivity or not. I can access the network state by using
private Boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); }But this just returns whether the mobile is connected to internet or not. I want to know if there is internet availability after connecting. Like, may be the server is down or internet not available. Please let me know how to accomplish this!
最满意答案
试试这样,
URL url = new URL("Your URL"); URLConnection conexion = url.openConnection(); conexion.setConnectTimeout(10000); // Don't forget to put a time limit conexion.connect();超时后(上述示例为10秒),它将超时异常。 因此,您可以使用它来检查Internet访问是否可用。
Try like this,
URL url = new URL("Your URL"); URLConnection conexion = url.openConnection(); conexion.setConnectTimeout(10000); // Don't forget to put a time limit conexion.connect();After timeout (10 secs for above mentioned example), It will through time out exception. So You can use it to check whether Internet access is available or not.
更多推荐
发布评论