• Android检测网络是否可用并获取网络类型


    在类中使用getSystemService的时候需要这样进行使用:1.

    public class JajaMenu extends Activity 
    {
        public static JajaMenu instance;
        
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            super.init();
            instance=this;
        }
        
      //获取实例
          public static JajaMenu getInstance(){
              return instance;
          }
    }

    2.调用

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;
    /**
         * 检测网络是否可用
         * @return
         */
        public boolean isNetworkConnected(){
            ConnectivityManager cm=(ConnectivityManager)JajaMenu.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo=cm.getActiveNetworkInfo();
            return networkInfo !=null && networkInfo.isConnectedOrConnecting();
        }
        
        /**
         * 获取网络类型
         * @return 0:没有网络   1:WIFI网络   2:WAP网络    3:NET网络
         * */
        public int getNetworkType(){
            int netType=0;
            ConnectivityManager cm=(ConnectivityManager)JajaMenu.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo=cm.getActiveNetworkInfo();
            if(networkInfo == null){
                return netType;
            }
            int nType=networkInfo.getType();
            if(nType ==ConnectivityManager.TYPE_MOBILE){
                String extraInfo=networkInfo.getExtraInfo();
                if(!extraInfo.isEmpty()){
                    String strInfo=extraInfo.toLowerCase();
                    if(strInfo.equals("cmnet")){
                        netType=NETTYPE_CMNET;
                    }
                    else{
                        netType=NETTYPE_CMWAP;
                    }
                }
            }
            else if(nType ==ConnectivityManager.TYPE_WIFI){
                netType=NETTYPE_WIFI;
            }
            return netType;
        }
  • 相关阅读:
    常用模块——time模块,datetime模块
    开发目录的规范

    模块
    day17作业
    面向过程编程
    函数递归
    谈谈作为一个菜B的培训感受
    絮叨机房精密空调的制冷剂
    接入机房产生冷凝水
  • 原文地址:https://www.cnblogs.com/ToFlying/p/4233861.html
Copyright © 2020-2023  润新知