Search code examples
androidinternet-connection

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


Solution

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