How to check currently internet connection is available or not in android

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

  • Setting the proxy for android's DownloadManager class
  • 'Must Override a Superclass Method' Errors after importing a project into Eclipse
  • Pass data from Activity to Service using an Intent
  • Difference between setContentView and LayoutInflater
  • Problems loading mobile.twitter in webview
  • Force subclasses to set a variable in java
  • How to save SMS to inbox in android?
  • Android - Why does onItemLongClick(…) return a boolean?
  • Small Popup for Instructions, like foursquare ones
  • How to construct a SQLite query to GROUP by ORDER?
  • How big is small, normal, large and xlarge?
  • How to add manifest permission to android application?
  • 8 Solutions collect form web for “How to check currently internet connection is available or not in android”

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

    boolean connected = false;
    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
            connected = true;
        }
        else
            connected = false;
    

    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" />
    

    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 1×1 PNG image or 1-byte text file.

    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" />
    

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

    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" />
    

    Use the method checkConnectivity:

      if (checkConnectivity() == 1){
        //do something 
    
        }
    

    Method to check your connectivity:

    private int checkConnectivity() {
            boolean enabled = true;
    
            ConnectivityManager connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = connectivityManager.getActiveNetworkInfo();
    
            if ((info == null || !info.isConnected() || !info.isAvailable())) {
                internet = 0;//sin conexion
                Toast.makeText(getApplicationContext(), "Sin conexión a Internet...", Toast.LENGTH_SHORT).show();
                enabled = false;
            } else {
                internet = 1;//conexión
            }
    
            return internet;
        }
    
    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>
    

    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" />
    
    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.