Android之判断网络状态(不过时)

public class NetworkUtils {

    /**
     * 判断网络是否连接
     *
     * @return true有网络连接 false无网络连接
     */
    public static boolean isConnected(Context context) {
        return isNetworkConnected(context);
    }

    private static boolean isNetworkConnected(Context context) {
        try {
            if (context != null) {
                ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                if (connectivityManager != null) {
                    NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
                    if (networkCapabilities != null) {
                        boolean isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
                        boolean isCellular = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
                        boolean isEthernet = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET);
                        LogUtil.logD("NetworkUtils", "wifi: " + isWifi);
                        LogUtil.logD("NetworkUtils", "Cellular: " + isCellular);
                        LogUtil.logD("NetworkUtils", "Ethernet: " + isEthernet);
                        return isWifi || isCellular || isEthernet;
                    }
                }
            }
            return false;
        } catch (Exception e) {
            LogUtil.logD("NetworkUtils", "error: " + e.getMessage());
            return false;
        }
    }

}

如果isConnected方法返回true,则表示此时设备有网络。