安卓--网络/GPS/WIFI/3G是否打开的简单封装

来源:互联网 发布:php会员登录代码 编辑:程序博客网 时间:2024/05/10 17:47
package com.sdp.panda.weatherquery.utils;import android.app.LoaderManager;import android.content.Context;import android.location.LocationManager;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.telephony.TelephonyManager;import android.widget.Toast;import java.util.List;/** * Created by 80926 on 2016/12/7. */public class NetUtils {    private static ConnectivityManager cm;    private static NetUtils instance;    private Context mContext;    private NetUtils(Context context) {        cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);        this.mContext = context;    } /**     * 判断网络是否打开     *     * @param context     * @return     */    public static NetUtils getNetUtils(Context context) {        if (instance == null) {            synchronized (NetUtils.class) {                if (instance == null) {                    instance = new NetUtils(context);                }            }        }        return instance;    }    public boolean isNetworkAvailable() {        if (cm != null) {            NetworkInfo[] infos = cm.getAllNetworkInfo();            if (infos != null) {                for (int i = 0; i < infos.length; i++) {                    if (infos[i].getState() == NetworkInfo.State.CONNECTED) {                        return true;                    }                }            }        }        return false;    }    /**     * 判读gps是否打开     *     * @return     */    public boolean isGpsEnabled() {        LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);        List<String> providers = lm.getProviders(true);        return providers != null && providers.size() > 0;    }    /**     * 判读WIFI是否打开     */    public boolean isWifiEnabled() {        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);        return ((cm.getActiveNetworkInfo() != null                && cm.getActiveNetworkInfo().getState() == NetworkInfo.State.CONNECTED) ||                tm.getNetworkType() == TelephonyManager.NETWORK_TYPE_UMTS);    }    /**     * 判读3G是否打开     */    public boolean is3GNet() {        NetworkInfo networkInfo = cm.getActiveNetworkInfo();        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {            return true;        }        return false;    }    /*    是否是wifi状态     */    public boolean isWifiStatue() {        NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();        if (activeNetworkInfo != null && activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {            return true;        }        return false;    }}
0 0
原创粉丝点击