android 判断网络连接是否可用

为了提高用户体验,我们在开发 android 应用的过程需要联网获取数据的时候我们首先要做的一步就是:

1.判断当前手机是否打开了网络,

2.打开了网络是否可以上网,

然后再去执行联网逻辑,避免没联网做不必要的工作!


通常情况下,我们是这样判断的

	public static boolean isNetAvailable(Context context) {
		ConnectivityManager connectManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        return (connectManager.getActiveNetworkInfo() != null);
	}

但是这样只完成了第一步,判断网络是否打开,

注意:打开并不代表就可以上网,

观察发现 NetworkInfo 有一个方法:

NetworkInfo.isAvailable()


官方的解释是

Indicates whether network connectivity is possible. A network is unavailable when a persistent or semi-persistent condition prevents the possibility of connecting to that network. Examples include 

The device is out of the coverage area for any network of this type. 
The device is on a network other than the home network (i.e., roaming), and data roaming has been disabled. 
The device's radio is turned off, e.g., because airplane mode is enabled. 
Returns:
true if the network is available, false otherwise

他列举了几种网络已连接但不可以上网的情况,

所以我们这样改改就好了:

public static boolean isNetAvailable(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        NetworkInfo info = manager.getActiveNetworkInfo();
        return (info != null && info.isAvailable());
	}


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android 中,我们可以通过以下代码来判断当前连接的代理是否可用: ```java public static boolean isProxyAvailable(Context context) { boolean isAvailable = false; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (cm != null) { NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo(); if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // 当前网络是WIFI,不需要代理 isAvailable = true; } else { String proxyHost = android.net.Proxy.getDefaultHost(); int proxyPort = android.net.Proxy.getDefaultPort(); if (proxyHost != null && proxyPort != -1) { // 代理可用 SocketAddress proxyAddress = new InetSocketAddress(proxyHost, proxyPort); Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress); try { URL url = new URL("http://www.baidu.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); conn.setConnectTimeout(3000); conn.setReadTimeout(3000); int responseCode = conn.getResponseCode(); if (responseCode == 200) { // 代理可用 isAvailable = true; } } catch (IOException e) { // 代理不可用 e.printStackTrace(); } } else { // 当前没有代理 isAvailable = true; } } } return isAvailable; } ``` 这个方法首先判断当前网络是否是 WIFI,如果是,则不需要代理就可以访问网络,直接返回 true。如果当前网络不是 WIFI,则判断是否设置了代理。如果设置了代理,则通过访问百度网站来判断代理是否可用。如果代理可用,则返回 true,否则返回 false。如果当前网络没有设置代理,则直接返回 true。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值