服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android中判断网络连接状态的方法

Android中判断网络连接状态的方法

2021-05-27 15:43Android开发网 Android

App判断用户是否联网是很普遍的需求,这篇文章主要介绍了Android中判断网络连接状态的方法,感兴趣的朋友可以参考一下

app判断用户是否联网是很普遍的需求,实现思路大概有下面几种

  • 利用android自带的connectivitymanager类
  • 有时候连上了wifi,但这个wifi是上不了网的,我们可以通过ping www.baidu.com来判断是否可以上网
  • 也可以利用get请求访问www.baidu.com,如果get请求成功,说明可以上网

1、判断网络是否已经连接

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// check all network connect, wifi or mobile
public static boolean isnetworkavailable(final context context) {
  boolean haswifocon = false;
  boolean hasmobilecon = false;
 
  connectivitymanager cm = (connectivitymanager) context.getsystemservice(context.connectivity_service);
  networkinfo[] netinfos = cm.getallnetworkinfo();
  for (networkinfo net : netinfos) {
 
    string type = net.gettypename();
    if (type.equalsignorecase("wifi")) {
      levellogutils.getinstance().i(tag, "get wifi connection");
      if (net.isconnected()) {
        haswifocon = true;
      }
    }
 
    if (type.equalsignorecase("mobile")) {
      levellogutils.getinstance().i(tag, "get mobile connection");
      if (net.isconnected()) {
        hasmobilecon = true;
      }
    }
  }
  return haswifocon || hasmobilecon;
 
}

2、利用 ping 判断 internet 能够 请求成功
note:有时候连上了网络, 但却上不去外网

?
1
2
3
4
5
6
7
8
9
10
11
12
// network available cannot ensure internet is available
public static boolean isnetworkavailable(final context context) {
  runtime runtime = runtime.getruntime();
  try {
    process pingprocess = runtime.exec("/system/bin/ping -c 1 www.baidu.com");
    int exitcode = pingprocess.waitfor();
    return (exitcode == 0);
  } catch (exception e) {
    e.printstacktrace();
  }
  return false;
}

考虑到网络, 我们 ping 了www.baidu.com
国外的话可以 ping 8.8.8.8

3、其他方案 模拟 get 请求

也可以访问网址, 看 get 请求能不能成功

?
1
2
3
4
5
6
7
url url = new url("http://www.google.com");
httpurlconnection urlc = (httpurlconnection) url.openconnection();
urlc.setconnecttimeout(3000);
urlc.connect();
if (urlc.getresponsecode() == 200) {
  return new boolean(true);
}

以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。

延伸 · 阅读

精彩推荐