Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.content.Context;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;

public class Main {
    public static boolean isNetworkPresent(Context context) {
        boolean isNetworkAvailable = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        try {

            if (cm != null) {
                NetworkInfo netInfo = cm.getActiveNetworkInfo();
                if (netInfo != null) {

                    isNetworkAvailable = netInfo.isConnected();
                    //                    Toast.makeText(context, "Connecting...", Toast.LENGTH_SHORT).show();
                    //Log.d("NETWORK<<","Connecting...."+netInfo.getReason());
                }
            }
        } catch (Exception ex) {
            //Log.e("Network Avail Error", ex.getMessage());

        }
        //        check for wifi also
        if (!isNetworkAvailable) {

            WifiManager connec = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            State wifi = cm.getNetworkInfo(1).getState();
            if (connec.isWifiEnabled() && wifi.toString().equalsIgnoreCase("CONNECTED")) {
                isNetworkAvailable = true;
                //Log.d("WIFI NETWORK<<","WIFI connected");
            } else {

                isNetworkAvailable = false;
                // Log.d("WIFI Network<<","WIFI not connected");
            }

        }
        return isNetworkAvailable;

    }
}