• android检测当前网络是否可用


    在android程序中运行第一步就是检测当前有无可用网络 
    如果没有网络可用就退出程序 
    if (isConnect(this)==false) 
             {   
                new AlertDialog.Builder(this) 
                .setTitle("网络错误") 
                .setMessage("网络连接失败,请确认网络连接") 
                .setPositiveButton("确定", new DialogInterface.OnClickListener() { 
                @Override 
    public void onClick(DialogInterface arg0, int arg1) { 
    // TODO Auto-generated method stub 
    android.os.Process.killProcess(android.os.Process.myPid()); 
                     System.exit(0); 
    } 
    }).show(); 
    } 
    public static boolean isConnect(Context context) { 
     
            // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理) 
        try { 
            ConnectivityManager connectivity = (ConnectivityManager) context 
                    .getSystemService(Context.CONNECTIVITY_SERVICE); 
            if (connectivity != null) { 
     
                // 获取网络连接管理的对象 
                NetworkInfo info = connectivity.getActiveNetworkInfo(); 
     
                if (info != null&& info.isConnected()) { 
                    // 判断当前网络是否已经连接 
                    if (info.getState() == NetworkInfo.State.CONNECTED) { 
                        return true; 
                    } 
                } 
            } 
        } catch (Exception e) { 
    // TODO: handle exception 
        Log.v("error",e.toString()); 
    } 
            return false; 
        } 
    最后一点还得再manifest中添加权限 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  • 相关阅读:
    高精度计算模板
    P1108 低价购买 [DP][统计方案]
    POJ3349 Snowflake Snow Snowflakes [哈希]
    P1312 Mayan游戏 [深搜][模拟]
    P1378 油滴扩展[深搜]
    P1514 引水入城[搜索,线段覆盖]
    TYVJ1391 走廊泼水节
    【BZOJ1196】公路修建问题
    【BZOJ3624】免费道路
    【BZOJ2429】聪明的猴子
  • 原文地址:https://www.cnblogs.com/a354823200/p/3931592.html
Copyright © 2020-2023  润新知