获取手机网络状态的代码

之前网上有人使用方法判断手机网络状态代码如下:

  ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
            NetworkInfo mMobileNetworkInfo = connectivityManager.getNetworkInfo(0);
            if(mMobileNetworkInfo != null)
                return mMobileNetworkInfo.isAvailable();


            ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
            NetworkInfo mWiFiNetworkInfo = connectivityManager.getNetworkInfo(1);
            if(mWiFiNetworkInfo != null)
                return mWiFiNetworkInfo.isAvailable();


这个正常情况下没什么问题,但发现在有些机器上会不那么准确在3G的环境下wifi状态还是可用

所以建议通过获取网络State状态来判断,相对比较稳妥准确一些

		  ConnectivityManager connectivityManager = (ConnectivityManager)this.getSystemService("connectivity");
          NetworkInfo mWiFiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
          NetworkInfo mPhoneNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

mWiFiNetworkInfo.getState();
mPhoneNetworkInfo.getState()
//state 状态
//State.CONNECTED;State.DISCONNECTED;State.CONNECTING;State.UNKNOWN;State.DISCONNE//CTING;State.SUSPENDED


你可能感兴趣的:(代码)