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 java.util.Locale;

public class Main {
    public static final int NETTYPE_NONE = 0;
    public static final int NETTYPE_WIFI = 1;
    public static final int NETTYPE_MOBILE_GPRS = 2;
    public static final int NETTYPE_MOBILE_EDGE = 3;
    public static final int NETTYPE_MOBILE_3G = 4;
    public static final int NETTYPE_UNKNOW = 99;

    public static int getCurrentNetType(Context context) {

        int result = NETTYPE_NONE;

        NetworkInfo localNetworkInfo = getCurrentActiveNetworkInfo(context);

        if (localNetworkInfo == null) {

            return result;

        }

        if (localNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {

            if (localNetworkInfo.getType() == 1) {

                result = NETTYPE_WIFI;

            } else if (localNetworkInfo.getType() == 0) {

                String subTypeName = localNetworkInfo.getSubtypeName().toUpperCase(Locale.getDefault());

                if (subTypeName.indexOf("GPRS") > 1) {

                    result = NETTYPE_MOBILE_GPRS;

                } else if (subTypeName.indexOf("EDGE") > 1) {

                    result = NETTYPE_MOBILE_EDGE;

                } else {

                    result = NETTYPE_MOBILE_3G;

                }

            } else {

                result = NETTYPE_UNKNOW;

            }

        } else if (localNetworkInfo.getState() == NetworkInfo.State.CONNECTING) {

            result = NETTYPE_UNKNOW;

            System.out.println("connecting " + localNetworkInfo.getType());

        }

        return result;

    }

    private static NetworkInfo getCurrentActiveNetworkInfo(Context context) {

        ConnectivityManager connectivityManager = (ConnectivityManager) context

                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager != null)

            return connectivityManager.getActiveNetworkInfo();

        return null;

    }
}