很多android程序在打开时,都需要检测网络是否连接,或者GPS是否可用:

1.网络是否连接(包括Wifi和移动网络)


  1.     // 是否有可用网络    

  2.     private boolean isNetworkConnected() {    

  3.         ConnectivityManager cm =     

  4.                 (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);    

  5.         NetworkInfo network = cm.getActiveNetworkInfo();    

  6.         if (network != null) {    

  7.             return network.isAvailable();    

  8.         }    

  9.         return false;    

  10.     }    

2.wifi是否可用

  1.     // Wifi是否可用    

  2.     private boolean isWifiEnable() {    

  3.         WifiManager wifiManager = (WifiManager) mContext    

  4.                 .getSystemService(Context.WIFI_SERVICE);    

  5.         return wifiManager.isWifiEnabled();    

  6.     }  

3.GPS是否可用

  1.     // Gps是否可用    

  2.     private boolean isGpsEnable() {    

  3.         LocationManager locationManager =     

  4.                 ((LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE));    

  5.         return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);    

  6.     }