Android check internet connection

AndroidNetworkingAndroid Networking

Android Problem Overview


I want to create an app that uses the internet and I'm trying to create a function that checks if a connection is available and if it isn't, go to an activity that has a retry button and an explanation.

Attached is my code so far, but I'm getting the error Syntax error, insert "}" to complete MethodBody.

Now I have been placing these in trying to get it to work, but so far no luck... Any help would be appreciated.

public class TheEvoStikLeagueActivity extends Activity {
    private final int SPLASH_DISPLAY_LENGHT = 3000;
     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
     
        private boolean checkInternetConnection() {
            ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
            // ARE WE CONNECTED TO THE NET
            if (conMgr.getActiveNetworkInfo() != null
                    && conMgr.getActiveNetworkInfo().isAvailable()
                    && conMgr.getActiveNetworkInfo().isConnected()) {

                return true;

                /* New Handler to start the Menu-Activity
                 * and close this Splash-Screen after some seconds.*/
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        /* Create an Intent that will start the Menu-Activity. */
                        Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class);
                        TheEvoStikLeagueActivity.this.startActivity(mainIntent);
                        TheEvoStikLeagueActivity.this.finish();
                    }
                }, SPLASH_DISPLAY_LENGHT);
            } else {
                return false;
                   	 
                Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class);
                TheEvoStikLeagueActivity.this.startActivity(connectionIntent);
                TheEvoStikLeagueActivity.this.finish();
            }
        }
    }

            

Android Solutions


Solution 1 - Android

This method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}

in manifest,

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

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
    try {
		InetAddress ipAddr = InetAddress.getByName("google.com"); 
        //You can replace it with your name
            return !ipAddr.equals("");
			    
		} catch (Exception e) {
			return false;
	}
}

Solution 2 - Android

Check to make sure it is "connected" to a network:

public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

Check to make sure it is "connected" to a internet:

public boolean isInternetAvailable() {
    try {
        InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}

Permission needed:

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

https://stackoverflow.com/a/17583324/950427

Solution 3 - Android

You can simply ping an online website like google:

public boolean isConnected() throws InterruptedException, IOException {
    String command = "ping -c 1 google.com";
    return Runtime.getRuntime().exec(command).waitFor() == 0;
}

Solution 4 - Android

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.

This method works fine.

    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.

And also do not put this method inside onCreate or any other method. Put it inside a class and access it.

Solution 5 - Android

You can use following snippet to check Internet Connection.

> It will useful both way that you can check which Type of NETWORK > Connection is available so you can do your process on that way.

You just have to copy following class and paste directly in your package.

/**
 * @author Pratik Butani
 */
public class InternetConnection {

	/**
	 * CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
	 */
	public static boolean checkConnection(Context context) {
		final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connMgr != null) {
			NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

			if (activeNetworkInfo != null) { // connected to the internet
				// connected to the mobile provider's data plan
				if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
					// connected to wifi
					return true;
				} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
			}
		}
		return false;
	}
}

Now you can use like:

if (InternetConnection.checkConnection(context)) {
    // Its Available...
} else {
    // Not Available...
}

DON'T FORGET to TAKE Permission :) :)

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

You can modify based on your requirement.

Thank you.

Solution 6 - Android

The accepted answer's EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

Solution 7 - Android

You cannot create a method inside another method, move private boolean checkInternetConnection() { method out of onCreate

Solution 8 - Android

All official methods only tells whether a device is open for network or not,
If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt network detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

    @Override
    public void onConnectionSuccess() {
        Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFail(String msg) {
        Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
    }
}).execute();

Network Call from async Task

public class CheckNetworkConnection extends AsyncTask < Void, Void, Boolean > {
    private OnConnectionCallback onConnectionCallback;
    private Context context;

    public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
        super();
        this.onConnectionCallback = onConnectionCallback;
        this.context = con;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void...params) {
        if (context == null)
            return false;

        boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
        return isConnected;
    }

    @Override
    protected void onPostExecute(Boolean b) {
        super.onPostExecute(b);

        if (b) {
            onConnectionCallback.onConnectionSuccess();
        } else {
            String msg = "No Internet Connection";
            if (context == null)
                msg = "Context is null";
            onConnectionCallback.onConnectionFail(msg);
        }

    }

    public interface OnConnectionCallback {
        void onConnectionSuccess();

        void onConnectionFail(String errorMsg);
    }
}

Actual Class which will ping to server

class NetWorkInfoUtility {

    public boolean isWifiEnable() {
        return isWifiEnable;
    }

    public void setIsWifiEnable(boolean isWifiEnable) {
        this.isWifiEnable = isWifiEnable;
    }

    public boolean isMobileNetworkAvailable() {
        return isMobileNetworkAvailable;
    }

    public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
        this.isMobileNetworkAvailable = isMobileNetworkAvailable;
    }

    private boolean isWifiEnable = false;
    private boolean isMobileNetworkAvailable = false;

    public boolean isNetWorkAvailableNow(Context context) {
        boolean isNetworkAvailable = false;

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

        setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
        setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

        if (isWifiEnable() || isMobileNetworkAvailable()) {
            /*Sometime wifi is connected but service provider never connected to internet
            so cross check one more time*/
            if (isOnline())
                isNetworkAvailable = true;
        }

        return isNetworkAvailable;
    }

    public boolean isOnline() {
        /*Just to check Time delay*/
        long t = Calendar.getInstance().getTimeInMillis();

        Runtime runtime = Runtime.getRuntime();
        try {
            /*Pinging to Google server*/
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
            int exitValue = ipProcess.waitFor();
            return (exitValue == 0);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            long t2 = Calendar.getInstance().getTimeInMillis();
            Log.i("NetWork check Time", (t2 - t) + "");
        }
        return false;
    }
}

Solution 9 - Android

No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

You can also use requestRouteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

You will also need:

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

in your android manifest.

for more detail go here

Solution 10 - Android

Use this method:

public static boolean isOnline() {
	ConnectivityManager cm = (ConnectivityManager) context
			.getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo netInfo = cm.getActiveNetworkInfo();
	return netInfo != null && netInfo.isConnectedOrConnecting();
}

This is the permission needed:

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

Solution 11 - Android

Try the following code:

public static boolean isNetworkAvailable(Context context) {
		boolean outcome = false;

		if (context != null) {
			ConnectivityManager cm = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);

			NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

			for (NetworkInfo tempNetworkInfo : networkInfos) {

				
				/**
				 * Can also check if the user is in roaming
				 */
				if (tempNetworkInfo.isConnected()) {
					outcome = true;
					break;
				}
			}
		}

		return outcome;
	}

Solution 12 - Android

1- create new java file (right click the package. new > class > name the file ConnectionDetector.java

2- add the following code to the file

package <add you package name> example com.example.example;

import android.content.Context;
import android.net.ConnectivityManager;
 
public class ConnectionDetector {
     
    private Context mContext;
     
    public ConnectionDetector(Context context){
        this.mContext = context;
    }
 
    public boolean isConnectingToInternet(){
    	
    	ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
		if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
		{
			return true; 
		}
		
		return false;

    }
}

3- open your MainActivity.java - the activity where you want to check connection, and do the following

A- create and define the function.

ConnectionDetector mConnectionDetector;</pre>

B- inside the "OnCreate" add the following

mConnectionDetector = new ConnectionDetector(getApplicationContext());

c- to check connection use the following steps

if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}

Solution 13 - Android

public boolean checkInternetConnection(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
        .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
        return false;
    } else {
        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;
}

Solution 14 - Android

in manifest

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

in code,

public static boolean isOnline(Context ctx) {
    if (ctx == null)
        return false;

    ConnectivityManager cm =
            (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

Solution 15 - Android

Use this code to check the internet connection

ConnectivityManager connectivityManager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if ((connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
				|| (connectivityManager
						.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
						.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
						.getState() == NetworkInfo.State.CONNECTED)) {
			return true;
		} else {
			return false;
		}

Solution 16 - Android

After "return" statement, you can't write any code(excluding try-finally block). Move your new activity codes before the "return" statements.

Solution 17 - Android

Here is a function which I use as a part of my Utils class:

public static boolean isNetworkConnected(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (cm.getActiveNetworkInfo() != null) && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

Use it like: Utils.isNetworkConnected(MainActivity.this);

Solution 18 - Android

This is the another option to handle all situation:

public void isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
    } else {
        Toast.makeText(ctx, "Internet Connection Is Required", Toast.LENGTH_LONG).show();

    }
}

Solution 19 - Android

I had issues with the IsInternetAvailable answer not testing for cellular networks, rather only if wifi was connected. This answer works for both wifi and mobile data:

https://stackoverflow.com/questions/5373930/how-to-check-network-connection-enable-or-disable-in-wifi-and-3gdata-plan-in-m

Solution 20 - Android

Check Network Available in android with internet data speed.

public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.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)
                      {
                    	  try
                    	    {
                    	        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
                    	        urlc.setRequestProperty("User-Agent", "Test");
                    	        urlc.setRequestProperty("Connection", "close");
                    	        urlc.setConnectTimeout(500); //choose your own timeframe
                    	        urlc.setReadTimeout(500); //choose your own timeframe
                    	        urlc.connect();
                    	        int networkcode2 = urlc.getResponseCode();
                    	        return (urlc.getResponseCode() == 200);
                    	    } catch (IOException e)
                    	    {
                    	        return (false);  //connectivity exists, but no internet.
                    	    }
                      }
 
          }
          return false;
    }

> This Function return true or false. > Must get user permission

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioniamlukeybView Question on Stackoverflow
Solution 1 - AndroidSeshu VinayView Answer on Stackoverflow
Solution 2 - AndroidJared BurrowsView Answer on Stackoverflow
Solution 3 - AndroidrazzView Answer on Stackoverflow
Solution 4 - AndroidBhargav JhaveriView Answer on Stackoverflow
Solution 5 - AndroidPratik ButaniView Answer on Stackoverflow
Solution 6 - AndroidHansView Answer on Stackoverflow
Solution 7 - AndroidMByDView Answer on Stackoverflow
Solution 8 - AndroidLokesh TiwariView Answer on Stackoverflow
Solution 9 - AndroidZar E AhmerView Answer on Stackoverflow
Solution 10 - AndroidIman MarashiView Answer on Stackoverflow
Solution 11 - AndroidPraful BhatnagarView Answer on Stackoverflow
Solution 12 - AndroidBahi HusseinView Answer on Stackoverflow
Solution 13 - AndroidAshish SainiView Answer on Stackoverflow
Solution 14 - AndroidR00WeView Answer on Stackoverflow
Solution 15 - AndroidFahimView Answer on Stackoverflow
Solution 16 - AndroidBurhan ARASView Answer on Stackoverflow
Solution 17 - AndroidMahendra LiyaView Answer on Stackoverflow
Solution 18 - AndroidZafer CelalogluView Answer on Stackoverflow
Solution 19 - AndroidRedPandaView Answer on Stackoverflow
Solution 20 - AndroidMd Imran ChoudhuryView Answer on Stackoverflow