Android随笔--项目中经常用到的网络工具类

 

写一个方法,判断网络是否可用.

Android随笔--项目中经常用到的网络工具类
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;

}
Android随笔--项目中经常用到的网络工具类

 

注解:

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:

  1. Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
  2. Send broadcast intents when network connectivity changes
  3. Attempt to "fail over" to another network when connectivity to a network is lost
  4. 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是否开启.

Android随笔--项目中经常用到的网络工具类
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;
    }
Android随笔--项目中经常用到的网络工具类

判断wifi是否打开:

Android随笔--项目中经常用到的网络工具类
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;
    }
Android随笔--项目中经常用到的网络工具类

if(activeNetInfo.getType()==ConnectivityManager.TYPE_MOBILE) {}... //判断3G网

Android随笔--项目中经常用到的网络工具类
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;
    }
Android随笔--项目中经常用到的网络工具类

Android随笔--项目中经常用到的网络工具类

上一篇:Ant自动编译打包&发布 android项目


下一篇:js验证邮箱、手机