在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()){<!–要继续执行的代码–>}

-完-

最新文章

  1. SQLite使用(三)&amp;&amp;核心API使用
  2. meta标签中的http-equiv属性使用介绍(转载)
  3. fuse入门
  4. PHP二维数组的分页
  5. OWASP top10
  6. chosen PersistenceUnitInfo does not specify a provider class name
  7. UESTC 1215 (思维题 旋转)
  8. 7.适配器模式(Adapter Pattern)
  9. Linux系统下如何禁止ping命令或允许ping命令的方法
  10. C#调用WebService实现天气预报 http://www.webxml.com.cn
  11. 子查询解嵌套not in 无法展开改写
  12. 我的第一篇文章 —— IE6的那些css常见bug(汇总)
  13. angular验证表单
  14. django模板语法之include
  15. iOS学习——内存泄漏检查及原因分析
  16. 制作用户登录界面(JAVA实现)
  17. centos7.4 调整根目录大小
  18. modifyGeoJSON
  19. AsyncTask的缺陷
  20. BZOJ3451:Tyvj1953 Normal

热门文章

  1. Android项目部署时,发生AndroidRuntime:android.view.InflateException: Binary XML file line #168: Error inflating class错误
  2. bzoj-4518 4518: [Sdoi2016]征途(斜率优化dp)
  3. Shell(C++实现,CodeBlocks+GCC编译)
  4. PHP数组操作
  5. [bzoj1911][Apio2010特别行动队] (动态规划+斜率优化)
  6. Membership 重置密码
  7. jQuery EasyUI视频教程合集
  8. Jsoup开发网站客户端第二篇,图片轮播,ScrollView兼容ListView
  9. JS/CSS缓存杀手——VS插件
  10. Spring Boot 添加Shiro支持