多语言展示
当前在线:142今日阅读:152今日分享:13

android 判断网络连接是否可用

开发的手机应用或多或少的都要使用到网络。网络连接是否可用,连接的是那种网络,这些状态都必须要去判断。以下就是一些常用的判断方法。我自己写成了一个工具类,方便平时使用。
工具/原料

编译工具:Eclipse

方法/步骤
1

判断连接的工具类类名:Network_status

2

/**  * 判断网络连接是否可用  * @param context  * @return  */ public static boolean is_Network_Available(Context context) {           ConnectivityManager cm = (ConnectivityManager) context                   .getSystemService(Context.CONNECTIVITY_SERVICE);           if (cm == null) {           } else {         //如果仅仅是用来判断网络连接         //则可以使用 cm.getActiveNetworkInfo().isAvailable();              NetworkInfo[] info = cm.getAllNetworkInfo();               if (info != null) {                   for (int i = 0; i < info.length; i++) {                       if (info[i].getState() == NetworkInfo.State.CONNECTED) {                           return true;                       }                   }               }           }           return false;       }

3

/**  * 判断GPS是否打开  * @param context  * @return  */ public static boolean is_Gps_Enabled(Context context) {           LocationManager lm = ((LocationManager) context                   .getSystemService(Context.LOCATION_SERVICE));           List accessibleProviders = lm.getProviders(true);           return accessibleProviders != null && accessibleProviders.size() > 0;       }

4

/**  * 判断WIFI是否打开  * @param context  * @return  */ public static boolean is_Wifi_Enabled(Context context) {           ConnectivityManager mgrConn = (ConnectivityManager) context                   .getSystemService(Context.CONNECTIVITY_SERVICE);           TelephonyManager mgrTel = (TelephonyManager) context                   .getSystemService(Context.TELEPHONY_SERVICE);           return ((mgrConn.getActiveNetworkInfo() != null && mgrConn                   .getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) || mgrTel                   .getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);       }

5

/**  * 判断是否是3G网络  * @param context  * @return  */ public static boolean is_3rd(Context context) {           ConnectivityManager cm = (ConnectivityManager) context                   .getSystemService(Context.CONNECTIVITY_SERVICE);           NetworkInfo networkINfo = cm.getActiveNetworkInfo();           if (networkINfo != null                   && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {               return true;           }           return false;       }

6

/**  * 判断是wifi还是3g网络  * @param context  * @return true(wifi)  */ public static boolean is_Wifi(Context context) {           ConnectivityManager cm = (ConnectivityManager) context                   .getSystemService(Context.CONNECTIVITY_SERVICE);           NetworkInfo networkINfo = cm.getActiveNetworkInfo();           if (networkINfo != null                   && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {               return true;           }           return false;       }

注意事项
1

本步骤需要一定代码基础

2

程序代码以代码片段的形式展示

推荐信息