android 开发中如何判断是否有网络连接

  1. public class IsInternet {  
  2.   
  3.     /** 
  4.      * 判断网络情况 
  5.      * @param context 上下文 
  6.      * @return false 表示没有网络 true 表示有网络 
  7.      */  
  8.     public static boolean isNetworkAvalible(Context context) {  
  9.         // 获得网络状态管理器  
  10.         ConnectivityManager connectivityManager = (ConnectivityManager) context  
  11.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  12.   
  13.         if (connectivityManager == null) {  
  14.             return false;  
  15.         } else {  
  16.             // 建立网络数组  
  17.             NetworkInfo[] net_info = connectivityManager.getAllNetworkInfo();  
  18.   
  19.             if (net_info != null) {  
  20.                 for (int i = 0; i < net_info.length; i++) {  
  21.                     // 判断获得的网络状态是否是处于连接状态  
  22.                     if (net_info[i].getState() == NetworkInfo.State.CONNECTED) {  
  23.                         return true;  
  24.                     }  
  25.                 }  
  26.             }  
  27.         }  
  28.         return false;  
  29.     }  
  30.   
  31.     // 如果没有网络,则弹出网络设置对话框  
  32.     public static void checkNetwork(final Activity activity) {  
  33.         if (!IsInternet.isNetworkAvalible(activity)) {  
  34.             TextView msg = new TextView(activity);  
  35.             msg.setText("当前没有可以使用的网络,请设置网络!");  
  36.             new AlertDialog.Builder(activity)  
  37.                     .setIcon(R.drawable.android)  
  38.                     .setTitle("网络状态提示")  
  39.                     .setView(msg)  
  40.                     .setPositiveButton("确定",  
  41.                             new DialogInterface.OnClickListener() {  
  42.   
  43.                                 public void onClick(DialogInterface dialog,  
  44.                                         int whichButton) {  
  45.                                     // 跳转到设置界面  
  46.                                     activity.startActivityForResult(new Intent(  
  47.                                             Settings.ACTION_WIRELESS_SETTINGS),  
  48.                                             0);  
  49.                                 }  
  50.                             }).create().show();  
  51.         }  
  52.         return;  
  53.     }  
  54. }  
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值