53

I want to execute my application offline also, so I need to check if currently an internet connection is available or not. Can anybody tell me how to check if internet is available or not in android? Give sample code. I tried with the code below and checked using an emulator but it's not working

public  boolean isInternetConnection() 
{ 

    ConnectivityManager connectivityManager =  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); 
} 

Thanks

Illidanek
  • 996
  • 1
  • 18
  • 32
mohan
  • 13,035
  • 29
  • 108
  • 178

31 Answers31

102

This will tell if you're connected to a network:

ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        
boolean connected = (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED);

Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected will still be true.

You will need this permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
james
  • 26,141
  • 19
  • 95
  • 113
  • 2
    hi. i have used same code in my application on Android 4.0 OS. but it is giving null pointer exception. – Vijay Bagul May 11 '12 at 11:08
  • possibly your android 4.0 device has no type_mobile connectivity – Arno den Hond Jun 10 '12 at 19:44
  • 2
    BTW, you also should check connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null, or you can get NullPointer on some tablets – uncle Lem Feb 12 '13 at 11:55
  • on "ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);" this line i get the error so i changed to "Context ctx=this; ConnectivityManager connectivityManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);" and it works – Rohan Pawar Apr 12 '13 at 11:30
  • 2
    Reading the Android documentation here http://developer.android.com/reference/android/net/ConnectivityManager.html shows that the getNetworkInfo usage above is deprecated but the method still exists taking a different parameter (a network rather than an int) – Fat Monk Jan 07 '16 at 10:12
  • `else` part is not required – suvojit_007 Jan 28 '19 at 12:56
  • Deprecated solution – Mkr Jul 21 '20 at 11:14
  • could someone explain if connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED is different than doing getNetworkInfo(..).isConnected() – thahgr Aug 27 '21 at 07:17
  • Simply help https://stackoverflow.com/a/54957599/10632772 – Asfar Hussain Siddiqui Dec 09 '22 at 10:24
28

You can use two method :

1 - for check connection :

   private boolean NetworkIsConnected() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

2 - for check internet :

  public boolean InternetIsConnected() {
        try {
            String command = "ping -c 1 google.com";
            return (Runtime.getRuntime().exec(command).waitFor() == 0);
        } catch (Exception e) {
            return false;
        }
    }

Add permissions to manifest :

 <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" />
Masoud Siahkali
  • 5,100
  • 1
  • 29
  • 18
  • 1
    Was looking for second one, to check if internet is available or not. Thanks. – Muhammad Rafique Jan 20 '20 at 17:35
  • 6
    I tested version 2 with the simulator (API 24, permissions are there) but it doesn't work: There's a network/internet connection but the code freezes the app (so do NOT run this on the main thread!), then returns "false" after about 10 seconds (no exception). Am I missing anything that's needed to make this work? – Neph Mar 25 '20 at 12:14
16

Also, be aware that sometimes the user will be connected to a Wi-Fi network, but that network might require browser-based authentication. Most airport and hotel hotspots are like that, so you application might be fooled into thinking you have connectivity, and then any URL fetches will actually retrieve the hotspot's login page instead of the page you are looking for.

Depending on the importance of performing this check, in addition to checking the connection with ConnectivityManager, I'd suggest including code to check that it's a working Internet connection and not just an illusion. You can do that by trying to fetch a known address/resource from your site, like a 1x1 PNG image or 1-byte text file.

Kuwame Brown
  • 533
  • 1
  • 10
  • 22
Bruno Oliveira
  • 5,056
  • 18
  • 24
  • 2
    Thanks for the post and welcome to Stackoverflow. As an FYI, you shouldn't include a signature in your posts here. – dave.c Mar 29 '11 at 15:26
13

Use Below Code:

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

if isNetworkAvailable() returns true then internet connection available, otherwise internet connection not available

Here need to add below uses-permission in your application Manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42
12

Deprecated on API 29.

getActiveNetworkInfo is deprecated from in API 29. So we can use it in bellow 29.

New code in Kotlin for All the API

fun isNetworkAvailable(context: Context): Boolean {
    val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
   
    // For 29 api or above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        val capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) ?: return false
        return when {
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ->    true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ->   true
            capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ->   true
            else ->     false
         }
    }
    // For below 29 api
    else {
        if (connectivityManager.activeNetworkInfo != null && connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting) {
            return true
        }
    }
    return false
}
Sanjayrajsinh
  • 15,014
  • 7
  • 73
  • 78
  • i still got capabilities == null when enable wifi button again, it's took about 30 seconds to capabilities != null – famfamfam Sep 12 '21 at 08:17
11
public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}

Google recommends this code block for checking internet connection. Because the device may have not internet connection even if it is connected to WiFi.

Samir Alakbarov
  • 1,120
  • 11
  • 21
6

Code :

    fun isInternetConnection(): Boolean {
    var returnVal = false
    thread {
        returnVal = try {
            khttp.get("https://www.google.com/")
            true
        }catch (e:Exception){
            false
        }
    }.join()
    return returnVal
}

Gradle:

implementation 'io.karn:khttp-android:0.1.0'

I use khttp because it's so easy to use.

So here in the above code if it successfully connects to google.com, it returns true else false.

5

use the next code:

public static boolean isNetworkAvaliable(Context ctx) {
    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;
    }
}

remember that yo need put in your manifest the next line:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
ogranada
  • 121
  • 1
  • 2
5

This code to check the network availability for all versions of Android including Android 9.0 and above:

public static boolean isNetworkConnected(Context  context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();
    // For 29 api or above
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
        return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR);
    } else return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Don't forget to add network-state permission in your manifest

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

Also, add @SuppressWarnings( "deprecation" ) before the method to avoid android studio deprecation warning.

4

You can just try to establish a TCP connection to a remote host:

public boolean hostAvailable(String host, int port) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port), 2000);
    return true;
  } catch (IOException e) {
    // Either we have a timeout or unreachable host or failed DNS lookup
    System.out.println(e);
    return false;
  }
}

Then:

boolean online = hostAvailable("www.google.com", 80);
Xiv
  • 8,862
  • 3
  • 27
  • 30
3

Here, is the method you can use. This works in all the APIs.

    public boolean isConnected() {
        ConnectivityManager cm = (ConnectivityManager) getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        }
        /* NetworkInfo is deprecated in API 29 so we have to check separately for higher API Levels */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Network network = cm.getActiveNetwork();
            if (network == null) {
                return false;
            }
            NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(network);
            if (networkCapabilities == null) {
                return false;
            }
            boolean isInternetSuspended = !networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED);
            return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                    && networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
                    && !isInternetSuspended;
        } else {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
    }
Mrudul Tora
  • 715
  • 8
  • 14
2

Kotlin

fun isOnline(context: Context): Boolean {
val connectivityManager =
    context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (connectivityManager != null) {
    val capabilities =
        connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
    if (capabilities != null) {
        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
            return true
        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
            return true
        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
            return true
        }
    }
}
return false}

Java

public static boolean isOnline(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

if (connectivityManager != null) {
    NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(connectivityManager.getActiveNetwork());
    if (capabilities != null) {
        if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR");
            return true;
        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI");
            return true;
        } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)) {
            Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET");
            return true;
        }
    }
}

return false;}
Sumit Ojha
  • 283
  • 2
  • 8
1

try using ConnectivityManager

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

Also Add permission to AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Jayanth
  • 5,954
  • 3
  • 21
  • 38
Amol Desai
  • 872
  • 1
  • 9
  • 17
1

Use the method checkConnectivity:

  if (checkConnectivity()){
    //do something 

    }

Method to check your connectivity:

private boolean checkConnectivity() {
        boolean enabled = true;

        ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();

        if ((info == null || !info.isConnected() || !info.isAvailable())) {
                            Toast.makeText(getApplicationContext(), "Sin conexión a Internet...", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            return true;
        }

        return false;
    }
Hamid
  • 1,493
  • 2
  • 18
  • 32
Cristofer
  • 1,046
  • 13
  • 21
1
  public  boolean isInternetConnection()
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            //we are connected to a network
            return  true;
        }
        else {
            return false;
        }
    }
anothernode
  • 5,100
  • 13
  • 43
  • 62
Ahmed Sayed
  • 155
  • 1
  • 2
1
public static   boolean isInternetConnection(Context mContext)
{
    ConnectivityManager connectivityManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        return  true;
    }
    else {
        return false;
    }
}
Ahmed Sayed
  • 155
  • 1
  • 2
  • This isn't really different from the accepted answer. Also, `isInternetConnection` is misleading since a device could be connected to a network with no internet provided in which case the function will return `true`. – Spikatrix Mar 06 '19 at 12:16
1

This function works fine...

public void checkConnection()
    {
        ConnectivityManager connectivityManager=(ConnectivityManager)

                this.getSystemService(Context.CONNECTIVITY_SERVICE);


  NetworkInfo wifi=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);


 NetworkInfo  network=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


        if (wifi.isConnected())
        {
           //Internet available

        }
        else if(network.isConnected())
        {
             //Internet available


        }
        else
        {
             //Internet is not available
        }
    }

Add the permission to AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Mir Rahed Uddin
  • 1,208
  • 2
  • 12
  • 25
1

This will show an dialog error box if there is not network connectivity

    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        new AlertDialog.Builder(this)
            .setTitle("Connection Failure")
            .setMessage("Please Connect to the Internet")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
    }
Malith Ileperuma
  • 926
  • 11
  • 27
1
public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Meysam Keshvari
  • 1,141
  • 12
  • 14
1

You can try this:

private boolean isConnectedToWifi(){
    ConnectivityManager cm = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
    if(cm != null){    
        NetworkCapabilities nc = cm.getNetworkCapabilities(cm.getActiveNetwork());
        return nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI);
    }
    return false;
}
Sourav
  • 312
  • 1
  • 8
1

getActiveNetworkInfo now Deprecated, just use getActiveNetwork

public boolean isNetworkConnected() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return connectivityManager.getActiveNetwork() != null;
}
dubenko
  • 199
  • 1
  • 2
1
 public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

This code works, add to manifest

<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" />
0
package com.base64;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import android.widget.Toast;

import com.androidquery.AQuery;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if(isConnectingToInternet(MainActivity.this))
        {
            Toast.makeText(getApplicationContext(),"internet is available",Toast.LENGTH_LONG).show();
        }
        else {
            System.out.print("internet is not available");
        }
    }

    public static boolean isConnectingToInternet(Context context)
    {
        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;
    }
}

/*  manifest */

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.base64">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Hardip
  • 360
  • 3
  • 9
0

Use ConnectivityManager Service

Source Link

...
...
import android.net.ConnectivityManager;
....
....
public class Utils {

   static ConnectivityManager connectivityManager;
   ....
   ....

    public static String isOnline(Context context) {
        JSONArray array = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("connected","false");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            Log.i("networkInfo", networkInfo.toString());
            jsonObject.put("connected",(networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected()));
            jsonObject.put("isAvailable",(networkInfo.isAvailable()));
            jsonObject.put("isConnected",(networkInfo.isConnected()));
            jsonObject.put("typeName",(networkInfo.getTypeName()));
            array.put(jsonObject);
            return array.toString();


        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        array.put(jsonObject);
        return array.toString();
    }

}
Code Spy
  • 9,626
  • 4
  • 66
  • 46
0
public boolean isConnectedToInternet() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    return (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED);
}
0

add this permission to your Manifest

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

Using "getActiveNetworkInfo()" and "isConnectedOrConnecting()" will return true if the are network connectivity and not if there are a connection to internet. For example if you don't have signal and so you don't have internet it but your mobile has the data activated it will return true instead of false.

To truly check if internet is available you need to check for network connectivity and also check for internet connection! And you can check for internet connection, for example, by trying to ping a well know address (like google in my code)

This is the code, just use this code and call isInternatAvailable(context).

    private static final String CMD_PING_GOOGLE = "ping -c 1 google.com";

    public static boolean isInternetAvailable(@NonNull Context context) {
        return isConnected(context) && checkInternetPingGoogle();
    }

    public static boolean isConnected(@NonNull Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        } else {
            return false;
        }
    }

    public static boolean checkInternetPingGoogle(){
        try {
            int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
            return a == 0x0;
        } catch (IOException ioE){
            EMaxLogger.onException(TAG, ioE);
        } catch (InterruptedException iE){
            EMaxLogger.onException(TAG, iE);
        }
        return false;
    }
Z3R0
  • 1,011
  • 10
  • 19
0

I find that the current answer here are deprecated, so i find this easy solution

val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager 
if(connectivityManager.isActiveNetworkMetered)
   println("online")
  • connectivityManager.isActiveNetworkMetered does not directly check if the network has internet connectivity. It only checks if the network is metered or not. To check if the network has internet connectivity, you need to use the NetworkCapabilities object. – Psijic Jun 19 '23 at 11:35
0

The code that NOT run on the main thread.

private class HostIsAvailable extends AsyncTask<String, Boolean, Boolean>{

    public boolean hostIsAvailable(String host, int port) {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), 2000);
            return true;
        } catch (IOException e) {
            // Either we have a timeout or unreachable host or failed DNS lookup
            System.out.println(e);
            return false;
        }
    }


    @Override
    protected Boolean doInBackground(String... args) {
        String host = args[0];
        return hostAvailable(host,80);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        Toast.makeText(_context, "Internet connectivity result:"+result, Toast.LENGTH_SHORT).show();
        Log.d("tag","Internet connectivity result:"+result);
        if(result) {
            //TODO: your code...
        }
        else
        {
            // TODO: refresh button
        }
    }
}

usage:

HostIsAvailable ch = new HostIsAvailable();
    ch.execute("www.google.com");
Hamid
  • 1,493
  • 2
  • 18
  • 32
0

Starting with Android M you should do this instead:

public boolean isNetworkAvailable() {
    try {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getNetworkCapabilities(cm.getActiveNetwork()).hasCapability(NET_CAPABILITY_INTERNET);
    } catch (Exception e) {
        return false;
    }
}

And you must have this permission:

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

Modern version from Android manual

val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val currentNetwork = connectivityManager.activeNetwork
val caps = connectivityManager.getNetworkCapabilities(currentNetwork)
val hasInternet = caps?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true
Psijic
  • 743
  • 7
  • 20