Android 检查当前wifi是否可以有网,可以访问网络

NetworInfo.isAvailable和NetworkInfo.isConnected只表明网络连接是否已连上,不能表明连接是否可以访问互联网

要检查设备是否在线,有以下方法:

第一种:

@TargetApi(Build.VERSION_CODES.M)
public static boolean isNetworkOnline1(Context context) {
    boolean isOnline = false;
    try {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkCapabilities capabilities = manager.getNetworkCapabilities(manager.getActiveNetwork());  // need ACCESS_NETWORK_STATE permission
        isOnline = capabilities != null && capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return isOnline;
}

优点: 1.可以在UI线程上运行;2.快速准确。

缺点:需要 API >= 23 和兼容性问题。

第二种:

public static boolean isNetworkOnline2() {
    boolean isOnline = false;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec("ping -c 1 8.8.8.8");
        int waitFor = p.waitFor();
        isOnline = waitFor == 0;    // only when the waitFor value is zero, the network is online indeed

        // BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        // String str;
        // while ((str = br.readLine()) != null) {
        //     System.out.println(str);     // you can get the ping detail info from Process.getInputStream()
        // }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return isOnline;
}

优点: 1.可以在UI线程上运行;2.可以多次ping,统计min/avg/max延迟时间和丢包率。

缺点:有些手机不行如三星。

第三种

public static boolean isNetworkOnline3() {
    boolean isOnline = false;
    try {
        URL url = new URL("http://www.google.com"); // or your server address
        // URL url = new URL("http://www.baidu.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Connection", "close");
        conn.setConnectTimeout(3000);
        isOnline = conn.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return isOnline;
}

优点:可以在所有设备和 API 上使用。

缺点:操作耗时,不能在UI线程上运行。

第四种

public static boolean isNetworkOnline4() {
    boolean isOnline = false;
    try {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress("8.8.8.8", 53), 3000);
        // socket.connect(new InetSocketAddress("114.114.114.114", 53), 3000);
        isOnline = true;
    } catch (IOException e) {
        e.printStackTrace();
    }

    return isOnline;
}

优点:1.可以在所有设备和API上使用;2.相对快速准确。

缺点:操作耗时,不能在UI线程上运行。

本人用的是第四种:

class InternetCheck extends AsyncTask<Void, Void, Boolean> {

	private Consumer mConsumer;

	public interface Consumer {
		void accept(Boolean internet);
	}

	public InternetCheck(Consumer consumer) {
		mConsumer = consumer;
		execute();
	}

	@Override
	protected Boolean doInBackground(Void... voids) {
		try {
			Socket sock = new Socket();
			sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
			sock.close();
			return true;
		} catch (IOException e) {
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean internet) {
		mConsumer.accept(internet);
	}
}
new InternetCheck(new InternetCheck.Consumer() {
				@Override
				public void accept(Boolean internet) {
					if (internet){
						//
					}else{
						//
					}
				}
			});

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值