Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.content.Context;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    public static boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection connection = (HttpURLConnection) (new URL(
                        "http://clients3.google.com/generate_204")).openConnection();
                connection.setRequestProperty("User-Agent", "Test");
                connection.setRequestProperty("Connection", "close");
                connection.setReadTimeout(1500);
                connection.connect();
                return (connection.getResponseCode() == 204 && connection.getContentLength() == 0);
            } catch (IOException e) {
                Log.e("ERROR", "Error checking internet connection");
            }
        } else
            Log.e("ERROR", "No network available");
        return false;
    }

    private static boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        return info != null;
    }
}