[Android][工具类]NetWorkUtils

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

/**
 * 网络状态 工具类
 * 如:检测网络是否可用,获取网络类型
 *
 */
public class NetWorkUtils {
    /**
     * 检测网络是否可用
     *
     * @param context 上下文
     * @return 网络是否可用
     */
    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }


    private static final int NETTYPE_WIFI = 0x01;
    private static final int NETTYPE_CMWAP = 0x02;
    private static final int NETTYPE_CMNET = 0x03;

    /**
     * 获取当前网络类型
     *
     * @param context 上下文
     * @return 0:没有网络   1:WIFI网络   2:WAP网络    3:NET网络
     */
    public static int getNetworkType(Context context) {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!TextUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    /**
     * 获取当前网络类型
     *
     * @param context 上下文
     */
    public static String getNetworkTypeStr(Context context) {
        int i = getNetworkType(context);
        switch (i) {
            case 0:
                return "没有网络";
            case 1:
                return "WIFI网络";
            case 2:
                return "WAP网络";
            case 3:
                return " 3:NET网络";
        }
        return "";
    }
}

你可能感兴趣的:([Android][工具类]NetWorkUtils)