Android 判断是否有外网连接
作者:hebedich 时间:2022-12-02 21:48:13
Android里判断是否可以上网,常用的是如下方法:
/**
* 检测网络是否连接
*
* @return
*/
private boolean isNetworkAvailable() {
// 得到网络连接信息
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// 去进行判断网络是否连接
if (manager.getActiveNetworkInfo() != null) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false;
}
有时候我们连接上一个没有外网连接的WiFi或者有线就会出现这种极端的情况,目前Android SDK还不能识别这种情况,一般的解决办法就是ping一个外网。
/* @author suncat
* @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www.baidu.com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}
标签:Android,判断外网连接
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android 中StringBuffer 和StringBuilder常用方法
2023-10-29 08:39:26
一文告诉你为什么要重写hashCode()方法和equals()方法
2021-09-05 07:05:55
Android Webview与ScrollView的滚动兼容及留白处理的方法
2021-09-27 00:56:40
聊聊Java Double相加出现的怪事
2023-07-22 22:46:39
C#实现将字符串转换成日期格式的方法
2021-07-18 06:19:11
springBoot详解集成Swagger流程
2023-02-26 22:23:33
![](https://img.aspxhome.com/file/2023/0/89640_0s.png)
C#切换鼠标左右键习惯无需控制面板中修改
2021-08-06 04:44:44
通过spring注解开发,简单测试单例和多例区别
2023-11-06 09:18:31
![](https://img.aspxhome.com/file/2023/0/113410_0s.png)
C#实现简单的聊天窗体
2022-11-09 03:25:13
将项目上传到Maven中央仓库(2023最新版)
2022-11-24 18:25:12
![](https://img.aspxhome.com/file/2023/0/103970_0s.png)
springboot集成RestTemplate及常见的用法说明
2023-02-17 20:02:27
C#中使用IFormattable实现自定义格式化字符串输出示例
2023-05-31 23:34:04
![](https://img.aspxhome.com/file/2023/6/104226_0s.png)
SpringBoot应用jar包启动原理详解
2022-07-08 09:45:48
![](https://img.aspxhome.com/file/2023/2/69122_0s.png)
Android Gradle 三方依赖管理详解
2023-02-27 21:11:53
C#的File类实现文件操作实例详解
2022-08-03 14:33:44
![](https://img.aspxhome.com/file/2023/0/108650_0s.png)
c#汉诺塔的递归算法与解析
2022-08-13 08:13:59
![](https://img.aspxhome.com/file/2023/2/91372_0s.png)
C#设置与获取环境变量的方法详解
2021-09-03 20:55:29
解析ScrollView--仿QQ空间标题栏渐变
2021-06-20 22:44:54
![](https://img.aspxhome.com/file/2023/6/98656_0s.gif)
Java API文档的使用方法详解
2022-06-15 20:12:03
![](https://img.aspxhome.com/file/2023/5/85915_0s.png)
C#实现窗体淡入淡出效果的方法总结
2021-05-28 08:23:37