Skip to main content

android - How to check internet connection


        android:text="Check Internet Connection"


import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.Context;
import android.os.StrictMode;

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
                StrictMode is a developer tool which detects things you might be doing by
                accident and brings them to your attention so you can fix them.

                StrictMode is most commonly used to catch accidental disk or network access on the
                application's main thread, where UI operations are received and animations take
                place. Keeping disk and network operations off the main thread makes for much
                smoother, more responsive applications. By keeping your application's main
                thread responsive, you also prevent ANR dialogs from being shown to users.

                StrictMode policy applied to a certain thread.

                The policy is enabled by setThreadPolicy(StrictMode.ThreadPolicy).
                The current policy can be retrieved with getThreadPolicy().

                Note that multiple penalties may be provided and they're run in order from least to
                most severe (logging before process death, for example). There's currently no
                mechanism to choose different penalties for different detected actions.

                Creates StrictMode.ThreadPolicy instances. Methods whose names start with detect
                specify what problems we should look for. Methods whose names start with penalty
                specify what we should do when we detect a problem.

                You can call as many detect and penalty methods as you like. Currently order is
                insignificant: all penalties apply to all detected problems.

            public StrictMode.ThreadPolicy.Builder permitNetwork ()
                Disable detection of network operations.

            public static void setThreadPolicy (StrictMode.ThreadPolicy policy)
                Sets the policy for what actions on the current thread should be detected,
                as well as the penalty if such actions occur.

                Internally this sets a thread-local variable which is propagated across
                cross-process IPC calls, meaning you can catch violations when a system service
                or another process accesses the disk or network on your behalf.

                policy : the policy to put into place

        // Allow to permit network operation on main thread
        // Or use AsyncTask instead of using Runnable thread
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();


        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(;
        final Button btn = (Button) findViewById(;
        final TextView tv = (TextView) findViewById(;

        final ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFB227")));

        btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                Context context = getApplicationContext();
                boolean isNetworkConnected = NetworkStatus.isNetworkConnected(context);
                boolean isInternetConnected = NetworkStatus.isInternetConnected();

                    tv.setText("Network connected.");
                else {
                    tv.setText("No network.");

                    tv.setText(tv.getText()+"\nInternet connection available.");
                else {

                    tv.setText(tv.getText()+"\nNo internet connection.");


import android.content.Context;

public class NetworkStatus {

    // Custom method to check network connection status
    public static boolean isNetworkConnected(Context context){
                Class that answers queries about the state of network connectivity. It also
                notifies applications when network connectivity changes. Get an instance of
                this class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE).

                Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)
                Send broadcast intents when network connectivity changes.
                Attempt to "fail over" to another network when connectivity to a network is lost.

            public abstract Object getSystemService (String name)
                Return the handle to a system-level service by name. The class
                of the returned object varies by the requested name.

                Interface to global information about an application environment. This is an
                abstract class whose implementation is provided by the Android system. It allows
                access to application-specific resources and classes, as well as up-calls for
                application-level operations such as launching activities,
                broadcasting and receiving intents, etc.

            public static final String CONNECTIVITY_SERVICE
                Use with getSystemService(Class) to retrieve a ConnectivityManager
                for handling management of network connections.

                Constant Value: "connectivity"
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

                Describes the status of a network interface.
                Use getActiveNetworkInfo() to get an instance that represents
                the current network connection.

            public NetworkInfo getActiveNetworkInfo ()
                Returns details about the currently active default data network. When connected,
                this network is the default route for outgoing connections. You should always check
                isConnected() before initiating network traffic. This may return null when
                there is no default network.

                This method requires the caller to hold the permission ACCESS_NETWORK_STATE.

                a NetworkInfo object for the current default network or null if no
                default network is currently active.
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

            public boolean isConnected ()
                Indicates whether network connectivity exists and it is possible to
                establish connections and pass data.

                Always call this before attempting to perform data transactions.

                true if network connectivity exists, false otherwise.

            public boolean isConnectedOrConnecting ()
                Indicates whether network connectivity exists or is in the process of being
                established. This is good for applications that need to do anything related
                to the network other than read or write data. For the latter, call
                isConnected() instead, which guarantees that the network is fully usable.

                true if network connectivity exists or is in the process of being established,
                false otherwise.
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        return isConnected;

    // Custom method to check internet connection
    public static boolean isInternetConnected(){
        boolean status = false;
                    An Internet Protocol (IP) address. This can be either an IPv4 address or an
                    IPv6 address, and in practice you'll have an instance of either Inet4Address
                    or Inet6Address (this class cannot be instantiated directly). Most code does
                    not need to distinguish between the two families, and should use InetAddress.

                public static InetAddress getByName (String host)
                    Returns the address of a host according to the given host string name host.
                    The host string may be either a machine name or a dotted string IP address.
                    If the latter, the hostName field is determined upon demand. host can be
                    null which means that an address of the loopback interface is returned.

                        host : the hostName to be resolved to an address or null.

                        the InetAddress instance representing the host.

                        UnknownHostException : if the address lookup fails.


            InetAddress address = InetAddress.getByName("");

                status = true;
        }catch (Exception e) // Catch the exception
        return status;

AndroidManifest.xml (permission)

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

More android examples

Popular posts from this blog

How to use NumberPicker in Android

Table of contentsNumberPicker ExamplesetOnValueChangedListeneronValueChange()setWrapSelectorWheel()setMinValue()setMinValue()setMaxValue()NumberPicker with String ArraysetDisplayedValues()String Array1. NumberPicker Example activity_main.xml <RelativeLayout xmlns:android="" xmlns:tools="" android:id="@+id/rl" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity" android:background="#ffffff" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25dp" android:text="Select a number..." /> <NumberPicker android:id="@+id/np" …

TextView new line (multiline) in android

TextView new line (multiline) TextView display text on android app. by default, TextView show text on a single line, and if it is long then TextView take more lines to display its text. android developers can generate a new line on TextView both programmatically and syntactically. android developers can make a multiline TextView without splitting text to multiline by android:minLines attribute.

the following android example code demonstrate us how can we syntactically create a new line on TextView widget by xml layout file and string resource file.

the simplest way to create a new line on TextView is android:text attribute. android:text attribute allow us to display text on android app. we can add a simple '\n' to TextView text where we want to start a new line. in this way we can create a multiline TextView widget in android app. we can assign android:text attribute value by this way android:text="Line1 \n Line2 \n Line3" for a TextView widget. this value will…

How to change TextView font size in android

TextView font size TextView widget display text on android application. we can set or change TextView font size statically by declarative syntax in xml layout file or programmatically at run time in java file. even we can use an xml file source to define font size.

the following example code demonstrate us how can we define TextView font size in xml layout file and how can we uses dimens.xml to reference font size. in this example we did not changes any coding in java file, so here we only include the layout xml file and dimens.xml file. activity_main.xml <LinearLayout xmlns:android="" xmlns:tools="" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="25dp" tools:context=".MainActivity" > <TextView android:id=&…