package com.base.utils.tools.android;

import android.content.Context;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import java.util.List;

/**
 * 手机是否联网工具类
 */

public class NetworkUtil {
    /**
     * 判断是否联网
     *
     * @param context
     * @return
     */
    public static boolean isNetworkAvailable(Context context) {
        // 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
        ConnectivityManager cm = getConnectivityManager(context);
        // 获取NetworkInfo对象
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        //判断NetworkInfo对象是否为空
        if (networkInfo != null) {
            return networkInfo.isAvailable();
        }

        return false;
    }

    /**
     * 判断GPS是否打开
     *
     * @param context
     * @return
     */

    public static boolean isGpsEnabled(Context context) {
        LocationManager lm = ((LocationManager) context.getSystemService(Context.LOCATION_SERVICE));
        List<String> accessibleProviders = lm.getProviders(true);
        return accessibleProviders != null && accessibleProviders.size() > 0;
    }

    /**
     * 判断WIFI是否打开
     *
     * @param context
     * @return
     */

    public static boolean isWifiEnabled(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        TelephonyManager mgrTel = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        return ((cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED)
                || mgrTel.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);
    }

    /**
     * 判断是否是移动网络
     *
     * @param context
     * @return
     */

    public static boolean isMobileConnected(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo != null
                && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
    }

    /**
     * 是否是Wifi连接
     *
     * @param context
     * @return
     */

    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = getConnectivityManager(context);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        return networkINfo != null
                && networkINfo.getType() == ConnectivityManager.TYPE_WIFI;
    }

    private static ConnectivityManager getConnectivityManager(Context context){
        return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    }
}

