Wednesday, September 30, 2015

android - How to check internet connection

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#cddfc3"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:textSize="25dp"
        android:textStyle="italic"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Check Internet Connection"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
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
                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.ThreadPolicy
                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.

            StrictMode.ThreadPolicy.Builder
                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.

            Parameters
                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();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

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

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

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

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

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

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

package com.cfsuman.me.androidcodesnippets;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.net.InetAddress;

public class NetworkStatus {

    // Custom method to check network connection status
    public static boolean isNetworkConnected(Context context){
        /*
            ConnectivityManager
                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.
        */

        /*
            Context
                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);

        /*
            NetworkInfo
                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.

            Returns
                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.

            Returns
                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.

            Returns
                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;
        try{
            /*
                InetAddress
                    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.

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

                    Returns
                        the InetAddress instance representing the host.

                    Throws
                        UnknownHostException : if the address lookup fails.

            */

            InetAddress address = InetAddress.getByName("google.com");

            if(address!=null)
            {
                status = true;
            }
        }catch (Exception e) // Catch the exception
        {
            e.printStackTrace();
        }
        return status;
    }
}

AndroidManifest.xml (permission)

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



More android examples