0

When I use the below code to show my connection state, "if" condition always returns "true", unless I put "netinfo" equal "null".

Where is the problem?

public boolean isConnectedToInternet()
{   
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if ( netInfo.isConnectedOrConnecting())
        {
            Toast.makeText(this, "On",Toast.LENGTH_LONG).show();
            Log.i("NewsList", "Internet Connection found.");
            return true;
        }

    Toast.makeText(this, "Off",Toast.LENGTH_LONG).show();
    return false;
}
ılǝ
  • 3,440
  • 2
  • 33
  • 47
spm
  • 80
  • 8
  • Check this http://stackoverflow.com/questions/18525924/android-ask-user-to-either-enable-wifi-or-quit-app/18526358#18526358 – Ritaban Sep 01 '13 at 08:40

1 Answers1

1

Try following:

DetectConnection.class:

public class DetectConnection {
    /*
     * Checking internet connection
     */
    public static boolean checkInternetConnection(Context context) {

        ConnectivityManager con_manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (con_manager.getActiveNetworkInfo() != null
                && con_manager.getActiveNetworkInfo().isAvailable()
                && con_manager.getActiveNetworkInfo().isConnected()) {
            return true;
        } else {
            return false;
        }
    }
}

Check internet from another activity:

if (DetectConnection.checkInternetConnection(this)) {
        //do something
}
fida1989
  • 3,234
  • 1
  • 27
  • 30