Android网络状态

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

/**
 * Created by LStar on 2017/3/9.
 * 网络状态工具类
 */
public class NetworkStateUtils {

    /**
     * 检查是否连接到网络
     */
    public static boolean networkConnected(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null) {
                return info.isAvailable();
            }
        }
        return false;
    }

    /**
     * 检查WIFI是否连接
     */
    public static boolean wifiConnected(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null) {
                if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    return info.isAvailable();
                }
            }
        }
        return false;
    }

    /**
     * 检查移动网络是否连接
     */
    public static boolean mobileConnected(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
                    return info.isAvailable();
                }
            }
        }
        return false;
    }

}

添加权限


广播监听网络状态

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by LStar on 2017/3/9.
 * 广播监听网络状态
 */
public class NetworkStateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String state = "网络连接:" + NetworkStateUtils.networkConnected(context) +
                ",WiFi连接:" + NetworkStateUtils.wifiConnected(context) +
                ",移动连接:" + NetworkStateUtils.mobileConnected(context);
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }

}

注册BroadcastReceiver


    
        
    

你可能感兴趣的:(Android网络状态)