3

i am trying to check internet connection in my android app

    public static boolean isConnectingToInternet(Context _context) {
    ConnectivityManager connectivity = (ConnectivityManager) _context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null) {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    Log.d("Network",
                            "NETWORKnAME: " + info[i].getTypeName());
                    return true;
                }

    }
    return false;
}

but problem is that when i try to check internet connection in emulator by turning off host PC internet connection still this function returning true that is internet available while i have turn off internet connection from host PC
ConnectivityManager class help in determining whether connected with the network not about the internet connectivity

my question is how to check internet connection is not available ?

MilapTank
  • 9,988
  • 7
  • 38
  • 53

2 Answers2

0

Try again after turning off wifi and data package..hope this helps.

user3606902
  • 829
  • 1
  • 10
  • 25
-2

Try this to detect your internet connection

public static boolean isInternetConnected(Context mContext) {

            try {
                ConnectivityManager connect = null;
                connect = (ConnectivityManager) mContext
                        .getSystemService(Context.CONNECTIVITY_SERVICE);

                if (connect != null) {
                    NetworkInfo resultMobile = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

                    NetworkInfo resultWifi = connect
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if ((resultMobile != null && resultMobile
                            .isConnectedOrConnecting())
                            || (resultWifi != null && resultWifi
                                    .isConnectedOrConnecting())) {
                        return true;
                    } else {
                        return false;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            return false;
        }

Add the following permissions to your manifest file,

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Confuse
  • 5,646
  • 7
  • 36
  • 58
Jatin
  • 1,650
  • 3
  • 17
  • 32
  • can you see my Question i have check connection using `ConnectivityManager` that is not working thats why i have asked here and you are check only two type of connection in my question i have check all type of connection – MilapTank Sep 26 '14 at 10:31