Android检测网络是否正常代码!
2024-08-24 05:18:07
在Android开发中,如果该应用程序需要连接网络请求,那么最好我们先做一个检测网络是否在线的判断,否则程序容易出现卡死或FC等Bug,应该判断如果手机离线则弹出提示让用户检查网络,如果正常则继续执行请求。
Android检测网络的方法:
在提交网络请求时执行该方法即可,如果检测到网络没有连接好,则会弹出提示框:“抱歉,目前无法连接网络。请检查您的手机网络连接!”并带有打开网络设置的按钮选项。
private boolean goToNetWork() {
// TODO Auto-generated method stub
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if(info == null || !info.isAvailable()){
new AlertDialog.Builder(this).setTitle("提醒:").setMessage("抱歉,目前无法连接网络。\n请检查您的手机网络连接!").setPositiveButton("打开网络设置",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent=null;
//判断手机系统的版本 即API大于10 就是3.0或以上版本
if(android.os.Build.VERSION.SDK_INT>10){
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
startActivity(intent);
}
}).setNegativeButton("联知道了!",null).show();
return false;
}
else{
//new AlertDialog.Builder(this).setMessage("网络正常可以使用").setPositiveButton("Ok", null).show();
return true;
}
调用方法:
if(goToNetWork()){<!–要继续执行的代码–>}
-完-
最新文章
- SQLite使用(三)&;&;核心API使用
- meta标签中的http-equiv属性使用介绍(转载)
- fuse入门
- PHP二维数组的分页
- OWASP top10
- chosen PersistenceUnitInfo does not specify a provider class name
- UESTC 1215 (思维题 旋转)
- 7.适配器模式(Adapter Pattern)
- Linux系统下如何禁止ping命令或允许ping命令的方法
- C#调用WebService实现天气预报 http://www.webxml.com.cn
- 子查询解嵌套not in 无法展开改写
- 我的第一篇文章 —— IE6的那些css常见bug(汇总)
- angular验证表单
- django模板语法之include
- iOS学习——内存泄漏检查及原因分析
- 制作用户登录界面(JAVA实现)
- centos7.4 调整根目录大小
- modifyGeoJSON
- AsyncTask的缺陷
- BZOJ3451:Tyvj1953 Normal
热门文章
- Android项目部署时,发生AndroidRuntime:android.view.InflateException: Binary XML file line #168: Error inflating class错误
- bzoj-4518 4518: [Sdoi2016]征途(斜率优化dp)
- Shell(C++实现,CodeBlocks+GCC编译)
- PHP数组操作
- [bzoj1911][Apio2010特别行动队] (动态规划+斜率优化)
- Membership 重置密码
- jQuery EasyUI视频教程合集
- Jsoup开发网站客户端第二篇,图片轮播,ScrollView兼容ListView
- JS/CSS缓存杀手——VS插件
- Spring Boot 添加Shiro支持