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
  • 2
  • 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

7 Answers7

3

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
  • 419
  • 2
  • 7
0

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
  • 754
  • 1
  • 8
  • 26
  • 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
0

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,373
  • 1
  • 18
  • 26
0

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
  • 292
  • 2
  • 17
0

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
  • 526
  • 5
  • 21
0

I have written a custom class that checks all possible networks either WIFI or Mobile data. Try this:

public class NetworkManager {

    /**
     * Checking for all possible internet providers
     * **/
    public static boolean isConnectingToInternet(Activity activity){

        ConnectivityManager connectivityManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Network[] networks = connectivityManager.getAllNetworks();
            NetworkInfo networkInfo;
            for (Network mNetwork : networks) {
                networkInfo = connectivityManager.getNetworkInfo(mNetwork);
                if (networkInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    return true;
                }
            }
        }else {
            if (connectivityManager != null) {
                //noinspection deprecation
                NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
                if (info != null) {
                    for (NetworkInfo anInfo : info) {
                        if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
//                            LOGD(TAG, "NETWORKNAME: " + anInfo.getTypeName());
                            return true;
                        }
                    }
                }
            }
        }
        showInternetSettingsAlert(activity);
        return false;
    }


    /**
     * Display a dialog that user has no internet connection lauch Settings
     * Options
     * */
    public static void showInternetSettingsAlert(final Activity activity) {

        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity, R.style.AppCompatAlertDialogStyle);

                // Setting Dialog Title
                alertDialog.setTitle("Internet Settings");

                alertDialog.setCancelable(false);

                // Setting Dialog Message
                alertDialog
                        .setMessage("Internet is not enabled. Do you want to go to settings menu?");

                // On pressing Settings button
                alertDialog.setPositiveButton("Settings",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                if(activity instanceof BaseFragmentActivity)
                                    ((BaseFragmentActivity)activity).hideLoader();
                                else if(activity instanceof BaseActivity)
                                    ((BaseActivity)activity).hideLoader();
//                        take user to turn Wifi screen
//                        activity.startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));

//                        take user to turn on mobile data screen
                                activity.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));


                            }
                        });

                // on pressing cancel button
                alertDialog.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                                dialog.cancel();
                            }
                        });
                // Showing Alert Message
                alertDialog.show();
            }
        });


    }

}

If network is unavailable it redirects user to turn on the network.

Mayank Bhatnagar
  • 2,772
  • 1
  • 13
  • 19
-1

Please check u have this code in manifest file

<uses-permission android:name="android.permission.INTERNET" />

Try This

ConnectivityManager cm = (ConnectivityManager) 
        activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
Bala Raja
  • 611
  • 6
  • 20