275

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...

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();
            }
        }
    }

            
Francesco - FL
  • 603
  • 1
  • 4
  • 25
iamlukeyb
  • 6,487
  • 12
  • 29
  • 40
  • 1
    The best answer resides here http://stackoverflow.com/a/27312494/1708390 . Just ping and see if device is actually connected to the Internet – Bugs Happen Jan 05 '17 at 05:32
  • If anyone wants to check the official document of 'ConnectivityManager' can visit: https://developer.android.com/training/monitoring-device-state/connectivity-monitoring – Kalu Khan Luhar Jan 04 '19 at 10:49

20 Answers20

496

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;
    }
}
Samir Alakbarov
  • 1,120
  • 11
  • 21
Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
  • hi seshu thanks for replying how do i get it to go to another activity if it detects no internet connection? – iamlukeyb Mar 05 '12 at 16:59
  • Heres what I've done but its still not going to the correct activity if (ni == null) { // There are no active networks. Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this,InfoActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); return false; } else return true; } – iamlukeyb Mar 05 '12 at 17:12
  • its a splash screen at the moment that goes for 3 seconds and then goes to a intro activity but I'm wanting it to check internet connection before and provide an if statement. if internet is connected then run the splash if not go to another activity. but at the moment it just runs through the splash and goes to the intro activity – iamlukeyb Mar 05 '12 at 17:27
  • 77
    This answer is incorrect. If you're connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo's javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you're on the internet. I'm looking into it further but you might have to ping a server on the internet to make sure you're actually on the internet. – miguel Jan 31 '14 at 01:42
  • 4
    Does it check for 3G,EDGE,GPRS,... too? – Dr.jacky Jul 07 '14 at 12:48
  • @miguel Check my updated answer. It should solve your usecase. – Seshu Vinay Aug 08 '14 at 06:40
  • How to find, connected to wifi but not actually active data on wifi. – Ganesh Katikar Aug 14 '14 at 11:29
  • @GaneshKatikar Check the edit. isInternetAvailable() addresses your case. – Seshu Vinay Aug 16 '14 at 04:49
  • 29
    be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection. – Oren Apr 07 '15 at 14:44
  • @Oren Of Course. It shouldn't be running on the main thread. – Seshu Vinay Apr 08 '15 at 04:56
  • 8
    isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G. – Yster Dec 10 '15 at 10:37
  • This does not detect that I have no internet connection inside the "Telekom" hotspot network. It can resolve the google IP: `google.com/216.58.210.238`. – Timo Bähr Apr 05 '16 at 11:14
  • @TimoBähr If it's able to give google's IP address, then it's connected to internet. – Seshu Vinay Apr 05 '16 at 11:22
  • 2
    The first part works in the main thread, the second part (the edit) only works if not on the main thread. – Dale May 19 '16 at 17:07
  • 1
    Why use InetAddress to check if we can get access to the internet if we have methods in the SDK to check if isAvailable() and isConnected() to do the job! http://stackoverflow.com/a/41431609/250260 – Jorgesys Jan 02 '17 at 18:32
  • @Elenasys InetAddress doesn't require ACCESS_NETWORK_STATE permission where as isAvailable() and isConnected() do. Also InetAddress works when my server is not reachable for some reason but device is still connected to Internet. – Seshu Vinay Jan 03 '17 at 09:11
  • 1
    Both answers are wrong, first you just check if it is connected to wifi (it can be online through mobile data, or be connected to a wifi which doens't have gateway)... second just check the DNS resolution, and it's possible that GOOGLE [which is a pretty common name] is already cached, on the SO, or in the router or anywhere else but the connection is unavailable – Rafael Lima Jun 14 '18 at 21:44
  • 1
    I can see that everyone uses google as a test domain. Perhaps it would be better to use [a-m].root-servers.org – Diblo Dk Mar 14 '19 at 13:26
  • NetworkInfo class was deprecated in API level 29. See docs: developer.android.com/reference/android/net/NetworkInfo.html – Siarhei Kavaleuski Sep 11 '19 at 19:43
  • [`getAllNetworkInfo()` is deprecated in API level 29](https://stackoverflow.com/a/53532456/7666442) – AskNilesh Sep 27 '19 at 08:35
  • 1
    `android.permission.ACCESS_WIFI_STATE` is not needed here. – Thomas Oct 27 '19 at 09:41
  • The first answer is deprecated and the second answer surely needs the job to done async – Kartikey Kumar Srivastava Apr 29 '20 at 18:11
  • Source code for InetAddress.equals() is set to always return false (Android 30) had to resort to tostring then equals – Richard Muvirimi Oct 05 '20 at 02:02
  • 3
    DNS addresses are cached. As a test, loop this method, then unplug your router from the internet. It keeps returning true... although it will eventually fail when the DNS cache times out (which varies a lot by DNS client). The only sure-fire way is to try and connect to something on the internet, and hope they don't mind you flooding them with connections. – Jeffrey Blattman Feb 05 '21 at 01:21
  • Actually, addresses are cached forever by the VM: "By default, when a security manager is installed, in order to protect against DNS spoofing attacks, the result of positive host name resolutions are cached forever."- https://developer.android.com/reference/java/net/InetAddress#getByAddress(byte[]) – Jeffrey Blattman Feb 05 '21 at 01:55
  • 1
    The edit made is absolutely wrong, DNS records are cached, if the person has open google ( who doesn't) it will return as long as the dns register lives, usually 24 hours... so this method is very wrong – Rafael Lima Oct 10 '21 at 22:42
  • The first approach always returns true in my case (even if I have no Internet connection) and the second one always returns false (even if I have an Internet connection). Any idea why this is happening? – VanessaF Nov 14 '21 at 10:29
103

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

Arpit Patel
  • 7,212
  • 5
  • 56
  • 67
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
82

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;
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
razz
  • 9,770
  • 7
  • 50
  • 68
  • This is returning false even I am connected to internet. Any idea? – Mahendra Chhimwal Oct 03 '16 at 07:06
  • 3
    Good one but not a best one.This whole logic depends on google.com lets suppose what if google is down for some minutes then you app won't be working for some minutes – Zeeshan Shabbir Nov 01 '16 at 07:13
  • @BugsHappen lol. When it comes to logic you can't lie on something unhandy. And some months ago, whole internet was down. Anything can happen bro. Perks of good and bad world. – Zeeshan Shabbir Jan 05 '17 at 05:33
  • 2
    so what do you suggest? – Bugs Happen Jan 05 '17 at 06:45
  • 10
    Well @ZeeshanShabbir is right , a solar flare to the part of the country of google's main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout :D – TheAnimatrix Jan 08 '17 at 15:41
  • 31
    If your app relys on a remote server (for authentication, fetching data, communication with database.... etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using `-i` option like this `ping -i 5 -c 1 www.myserver.com`. – razz Apr 28 '17 at 22:50
  • how to set time out ?? i want to ping only for 5 seconds if the ping not get response in 5 second it will return false else true....what i have to do for achieve this..?? . sorry for my english – Ajay Mistry Sep 19 '17 at 12:44
  • i use a head request to apps own server to check server availability in my app. after all my server counts not google server. – Amir Ziarati Dec 31 '17 at 08:15
  • 2
    Will this method falsely return true in scenarios where there is a wifi login page? – Foobar Jun 26 '18 at 16:41
  • 1
    @Roymunson I haven't tested it but it should return false because the pinged server won't be reachable until u log in. – razz Jun 26 '18 at 16:51
  • it returns false too late. not a good one – nafees ahmed Nov 12 '18 at 10:48
  • working perfectly for me. Thanks, @razzak. – Farhan Anwar Feb 01 '20 at 16:39
  • @razzak - so how long it take to response if I connected to wifi with no data? Did you handle it? – Arnold Brown Feb 11 '20 at 04:01
  • Forking your process is a super heavy weight method to accomplish this. See other answers. – Jeffrey Blattman Feb 05 '21 at 00:53
  • The argument -c was replaced by -n: "ping -n 1 google.com" – gustavoknz May 17 '21 at 15:14
  • @gustavoknz this code works on all phones but not on oneplus devices after oneplus 7 why is that any suggestions? – Shashank Mistry Apr 10 '22 at 15:12
  • Is there a method to show some screen while waiting? It works for me, but offline, it just blanks out the screen during the ping time. – Sriram Nadiminti Jul 08 '22 at 14:13
  • Shouldn't this really be using a timeout too, with `waitFor(timeout, TimeUnit.MILLISECONDS)`? – drmrbrewer Jul 11 '23 at 08:15
42

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.

Muhammed Refaat
  • 8,914
  • 14
  • 83
  • 118
Bhargav Jhaveri
  • 2,123
  • 1
  • 18
  • 23
  • 3
    This is a good approach to the problem. But probably a ping is enough – dazito May 27 '14 at 09:13
  • The difficulties that come with threading when you just need to simply check for internet response isn't worth the effort. Ping does the job with no struggle. – MbaiMburu Jul 25 '18 at 08:08
  • Best approach (period). Sockets, InetAddress methods are error prone specially when your device is connected to a Wifi network without an internet connection, it will continue to indicate that the internet is reachable even though it is not. – Gayal Rupasinghe Dec 17 '21 at 09:16
  • 1
    I used this one and works very well, today in late 2022, you need to use https and not http because runtime refuses to make a request in cleartext and with that exception you would always return false, as offline. changed http to https and works super well – Davide Piras Dec 10 '22 at 00:37
31

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.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
  • 1
    `android.permission.ACCESS_WIFI_STATE` is not needed here. – Thomas Oct 27 '19 at 09:41
  • You are checking whether wifi network or a cellular network is currently connected to the device. This way will not suffice for instance, when the device connects to a wifi network which doesn't have the capability to reach the internet. – Gayal Rupasinghe Dec 17 '21 at 09:20
24

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("");
}
Hans
  • 1,886
  • 24
  • 18
14

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;
    }
}
Cililing
  • 4,303
  • 1
  • 17
  • 35
Lokesh Tiwari
  • 10,496
  • 3
  • 36
  • 45
14

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

MByD
  • 135,866
  • 28
  • 264
  • 277
  • you can create a thread to do continuous look up of network availability and let you know and keep retrying after an interval. – Vipin Sahu Jan 25 '13 at 06:52
9

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

Community
  • 1
  • 1
Zar E Ahmer
  • 33,936
  • 20
  • 234
  • 300
7

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" />
Iman Marashi
  • 5,593
  • 38
  • 51
5

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;
    }
Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
  • heres what I've got so far private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { // There are no active networks. Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this,InfoActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); return false; } else return true; } – iamlukeyb Mar 05 '12 at 17:07
  • Please try the piece of code I posted to check whether the device can connect to remote server or not... – Praful Bhatnagar Mar 05 '12 at 20:15
4

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
}
Fatih Mert Doğancan
  • 1,016
  • 14
  • 21
Bahi Hussein
  • 433
  • 5
  • 10
3
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;
}
Nirmal
  • 9,391
  • 11
  • 57
  • 81
Ashish Saini
  • 2,328
  • 25
  • 21
3

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;
}
R00We
  • 1,931
  • 18
  • 21
3

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;
        }
Fahim
  • 12,198
  • 5
  • 39
  • 57
2

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

Burhan ARAS
  • 2,517
  • 25
  • 19
2

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);

Mahendra Liya
  • 12,912
  • 14
  • 88
  • 114
1

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();

    }
}
Jared Burrows
  • 54,294
  • 25
  • 151
  • 185
Zafer Celaloglu
  • 1,438
  • 1
  • 17
  • 28
1

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:

How to check network connection enable or disable in WIFI and 3G(data plan) in mobile?

Community
  • 1
  • 1
RedPanda
  • 522
  • 6
  • 15
1

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" />
Md Imran Choudhury
  • 9,343
  • 4
  • 62
  • 60