1
public class MainActivity extends AppCompatActivity {
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void show(View v){
        if (hasActiveInternetConnection(context)){
            Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
        }
    }

    public boolean hasActiveInternetConnection(Context context) {
        if (isNetworkAvailable(context)) {

            new URLConnectTask().execute();


        } else {
           // Log.d(LOG_TAG, "No network available!");
            Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    private class URLConnectTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            // params comes from the execute() call: params[0] is the url.
            try {
                HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                urlc.setRequestProperty("User-Agent", "Test");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                String code = String.valueOf(urlc.getResponseCode() == 200);
                return code;
            } catch (IOException e) {
                //Log.e(LOG_TAG, "Error checking internet connection", e);
                //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
                return "Error checking internet connection";
            }
        }
    }

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

I used this post for internet connectivity check. But as they are not using asynctask, if I use this code I'm getting NetworkOnMainThreadException. I tried using asynctask but now I'm only getting message "Internet connection not available". I think its because the asynctask is not returning boolean value true. So any help would be much appreciated.

Community
  • 1
  • 1
Sammy
  • 181
  • 3
  • 18
  • 1
    you have to add <>, inside your if condition (just after the new URLConnectTask().execute(); line ). Otherwise as default, it will return false as per your code – kishorepatel Feb 26 '16 at 08:55
  • Superb answer. Thanks. That;s what I was looking for. @kishorepatel – Sammy Feb 26 '16 at 09:00

5 Answers5

2

this work fine you can use this code

public boolean isConnectingToInternet(){
        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)
                      {
                          return true;
                      }

          }
          return false;
    }

//add to permission <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Rathod Vijay
  • 417
  • 2
  • 7
-1

Try this code

 public class MainActivity extends AppCompatActivity {
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}
}
 public void show(View v){
  if (isConnectingToInternet(context)){
    Toast.makeText(MainActivity.this, "Internet connection available", Toast.LENGTH_SHORT).show();
    new URLConnectTask().execute();
}else{
    Toast.makeText(MainActivity.this, "Internet connection not available", Toast.LENGTH_SHORT).show();
}
}

  public boolean isConnectingToInternet(){
 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)
          {
              return true;
          }

}
 return false;
}
}

private class URLConnectTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        // params comes from the execute() call: params[0] is the url.
        try {
            HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
            urlc.setRequestProperty("User-Agent", "Test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            String code = String.valueOf(urlc.getResponseCode() == 200);
            return code;
        } catch (IOException e) {
            //Log.e(LOG_TAG, "Error checking internet connection", e);
            //Toast.makeText(MainActivity.this, "Error checking internet connection", Toast.LENGTH_SHORT).show();
            return "Error checking internet connection";
        }
    }
  }
}
Amit Basliyal
  • 840
  • 1
  • 10
  • 28
  • I'm using HttpURLConnection to check if WiFi has active internet connection. Will this code do the same? @Amit – Sammy Feb 26 '16 at 08:51
  • I'm getting error in context. I don't understand how you are using two context(context and _context) @Amit – Sammy Feb 26 '16 at 09:17
  • `ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);` try this – Amit Basliyal Feb 26 '16 at 09:43
  • I tried ur code but when lan cable is removed from wifi, it still shows "Connection available". @Amit – Sammy Feb 26 '16 at 09:47
  • which device you checking real device or emulator – Amit Basliyal Feb 26 '16 at 09:49
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/104623/discussion-between-sam-and-amit). – Sammy Feb 26 '16 at 09:54
-1

use bellow method to check online

/***************** * Check isOnline ******************/

  public static boolean isOnline(Context context) {
        boolean result = false;
        if (context != null) {
            final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
                if (networkInfo != null) {
                    result = networkInfo.isConnected();
                }
            }
        }
        return result;
    }

make sure your manifest contains this permissions

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Bajirao Shinde
  • 1,356
  • 1
  • 18
  • 26
-1

You can use this class:

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {
private Context _context;

public ConnectionDetector(Context context){
    this._context = context;
}

public boolean isConnectingToInternet(){
    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)
                {
                    return true;
                }

    }
    return false;
}

}

Akbar
  • 430
  • 4
  • 18
-1

try this once,

 Boolean isInternetPresent = false;
isInternetPresent = findconn.isConnectingToInternet(); 
     if (isInternetPresent) {
            new URLConnectTask().execute();
        } else {
           // Log.d(LOG_TAG, "No network available!");
            Toast.makeText(MainActivity.this, "No network available!", Toast.LENGTH_SHORT).show();
        }

    public boolean isConnectingToInternet(){
            ConnectivityManager connectivity = (ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo info=connectivity.getActiveNetworkInfo();
            if (info == null) {
                return false;
            }
            else {
                return info.isConnectedOrConnecting();
            }
   }

(or) if you want individual network types

ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = connectivity.getActiveNetworkInfo();
            if (activeNetwork != null) { // connected to the internet
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    // connected to wifi
                    Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                    // connected to the mobile provider's data plan
                    Toast.makeText(context, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                }
            } else {
                // not connected to the internet
            }
Rgv
  • 504
  • 5
  • 23