Android check internet connection [duplicate]
Asked Answered
B

20

276

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

            
Bonney answered 5/3, 2012 at 16:30 Comment(2)
The best answer resides here https://mcmap.net/q/11339/-how-to-check-internet-access-on-android-inetaddress-never-times-out . Just ping and see if device is actually connected to the InternetRockingham
If anyone wants to check the official document of 'ConnectivityManager' can visit: developer.android.com/training/monitoring-device-state/…Vesuvian
S
495

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;
    }
}
Solubility answered 5/3, 2012 at 16:34 Comment(27)
hi seshu thanks for replying how do i get it to go to another activity if it detects no internet connection?Bonney
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; }Bonney
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 activityBonney
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.Heldentenor
Does it check for 3G,EDGE,GPRS,... too?Brazzaville
@Heldentenor Check my updated answer. It should solve your usecase.Solubility
How to find, connected to wifi but not actually active data on wifi.Letti
@GaneshKatikar Check the edit. isInternetAvailable() addresses your case.Solubility
be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection.Supernumerary
@Supernumerary Of Course. It shouldn't be running on the main thread.Solubility
isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G.Ontologism
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.Piecedyed
@TimoBähr If it's able to give google's IP address, then it's connected to internet.Solubility
The first part works in the main thread, the second part (the edit) only works if not on the main thread.Bootery
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! https://mcmap.net/q/11339/-how-to-check-internet-access-on-android-inetaddress-never-times-outDisagree
@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.Solubility
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 unavailableShoifet
I can see that everyone uses google as a test domain. Perhaps it would be better to use [a-m].root-servers.orgDisputation
NetworkInfo class was deprecated in API level 29. See docs: developer.android.com/reference/android/net/NetworkInfo.htmlCataract
getAllNetworkInfo() is deprecated in API level 29Marvelous
android.permission.ACCESS_WIFI_STATE is not needed here.Braces
The first answer is deprecated and the second answer surely needs the job to done asyncResee
Source code for InetAddress.equals() is set to always return false (Android 30) had to resort to tostring then equalsPedo
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.Loar
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."- developer.android.com/reference/java/net/…Loar
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 wrongShoifet
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?Fingerprint
K
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://mcmap.net/q/11339/-how-to-check-internet-access-on-android-inetaddress-never-times-out

Kriegspiel answered 20/4, 2013 at 20:35 Comment(9)
How to find, connected to wifi but not actually active data on wifi.Letti
Only tells you if you are connect to a network, and not the internet. If you want crashes (for internet safe code) then use this.Sybilla
@Jared you ruined introducing the hell contextPolliwog
How is this different from the accepted answer?Solubility
@SeshuVinay Read the date. I posted this over 4 years ago.Kriegspiel
My test device seem to cache the IP of the Google server, so isInternetAvailable always returns true for me. Using a different server would work, but it's not very reliable to do so. Can I do anything about the caching?Boswall
isInternetAvailable is pretty good answer, but there is a problem. If a user uses a vpn and the host is blocked then this method returns false.Ganley
getAllNetworkInfo() is deprecated in API level 29Marvelous
NetworkOnMainThreadException!Social
A
84

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;
}
Alost answered 9/12, 2015 at 10:3 Comment(18)
This is returning false even I am connected to internet. Any idea?Ras
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 minutesChampac
@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.Champac
so what do you suggest?Rockingham
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 :DBohn
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.Alost
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 englishCityscape
i use a head request to apps own server to check server availability in my app. after all my server counts not google server.Condescend
Will this method falsely return true in scenarios where there is a wifi login page?Stratification
@Roymunson I haven't tested it but it should return false because the pinged server won't be reachable until u log in.Alost
it returns false too late. not a good oneDimer
working perfectly for me. Thanks, @razzak.Electrophysiology
@razzak - so how long it take to response if I connected to wifi with no data? Did you handle it?Eldest
Forking your process is a super heavy weight method to accomplish this. See other answers.Loar
The argument -c was replaced by -n: "ping -n 1 google.com"Cila
@Cila this code works on all phones but not on oneplus devices after oneplus 7 why is that any suggestions?Gloriagloriana
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.Dashed
Shouldn't this really be using a timeout too, with waitFor(timeout, TimeUnit.MILLISECONDS)?Kuhn
H
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.

Heritor answered 6/2, 2014 at 5:48 Comment(4)
This is a good approach to the problem. But probably a ping is enoughSpavined
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.Mandie
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.Agace
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 wellUvea
S
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.

Silvester answered 21/10, 2015 at 10:4 Comment(2)
android.permission.ACCESS_WIFI_STATE is not needed here.Braces
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.Agace
G
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("");
}
Gatepost answered 16/12, 2015 at 19:48 Comment(5)
This worked out pretty well for a one odd check where I am not having to manage 'reachability' state.Longicorn
This method is returning false even if I am connected to internet. Any idea?Ras
This should be the accepted answer.Chaconne
Source code for InetAddress.equals() is set to always return false (Android 30) had to resort to tostring then equalsPedo
Useful Answer but sometimes i am getting ANR's at this line inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);Compensate
C
14

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

Celerity answered 5/3, 2012 at 16:32 Comment(1)
you can create a thread to do continuous look up of network availability and let you know and keep retrying after an interval.Balzer
P
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;
    }
}
Pieter answered 17/11, 2015 at 18:23 Comment(3)
please note Runtime can only be used in rooted applications as far as i knowSinglehandedly
best solution i found, it's detect if internet available while your are connected to wifi network or cell phone data great jobUnaccomplished
Unfortunately, Ping is not allowed on some samsung devices.Growler
K
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

Kroon answered 11/7, 2014 at 7:56 Comment(2)
this function return TRUE alwaysAlgernon
This is working for me . This link may help.. #1561288Kroon
T
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" />
Tate answered 19/12, 2015 at 15:39 Comment(1)
duplicate and inaccurately returns true with a non-internet routing connectionTheodosia
R
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;
    }
Reenter answered 5/3, 2012 at 16:58 Comment(2)
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; }Bonney
Please try the piece of code I posted to check whether the device can connect to remote server or not...Reenter
P
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
}
Potboiler answered 30/8, 2014 at 23:41 Comment(0)
M
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;
}
Mina answered 22/1, 2014 at 5:16 Comment(0)
S
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;
}
Sarcous answered 30/12, 2014 at 7:59 Comment(1)
android.permission.ACCESS_WIFI_STATE is not needed here.Braces
W
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;
        }
Wherever answered 17/3, 2015 at 12:29 Comment(0)
M
2

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

Moly answered 28/5, 2013 at 13:9 Comment(0)
O
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);

Onus answered 22/5, 2014 at 5:15 Comment(2)
Suppose the network is still connecting is it safe to proceed?Ephor
Depends on your use-case...Onus
R
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();

    }
}
Rosiarosicrucian answered 8/8, 2014 at 6:49 Comment(2)
ctx is the Context that must be global.Kriegspiel
yeah you are right!we need to define it as a global variableRosiarosicrucian
P
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?

Proscenium answered 20/12, 2014 at 21:24 Comment(0)
S
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" />
Saturation answered 15/4, 2015 at 7:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.