写一个方法,判断网络是否可用.
public static boolean isNetworkAvailable(Context context){ ConnectivityManager connectivity =(ConnectivityManager ) context.getSystemService(Context.CONNECTIVITY_SERVICE); if(connectivity ==null){ }else{ NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; }
注解:
ConnectivityManager类 看名字就能看出来是联网管理类,google官方解释是:
Class that answers queries about the state of network
connectivity. It also notifies applications when network
connectivity changes. Get an instance of this class by calling
Context.getSystemService(Context.CONNECTIVITY_SERVICE)
.
The primary responsibilities of this class are to:
- Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
- Send broadcast intents when network connectivity changes
- Attempt to "fail over" to another network when connectivity to a network is lost
- Provide an API that allows applications to query the coarse-grained or fine-grained state of the available networks
也就是他不会直接使用,通常是通过Context.getSystemService……来实现.
然后判断是否为空即可.比较简单.
Windows Live Writer也真不好用..唉.有什么好的编辑代码的工具..
另外一个需求是判断GPS是否开启.
public static boolean isGpsEnabled(Context context) { LocationManager locationManager = ((LocationManager) context .getSystemService(Context.LOCATION_SERVICE)); List<String> accessibleProviders = locationManager.getProviders(true); return accessibleProviders != null && accessibleProviders.size() > 0; }
判断wifi是否打开:
public static boolean isWifi(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; }
if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) {}... //判断3G网
public static boolean is3G(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) { return true; } return false; }