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="#d5dfd7"
    >
    <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.AsyncTask;
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 java.net.InetAddress;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        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 ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF63C569")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new CheckInternetConnection().execute();
           }
        });
    }

    /*
        AsyncTask
            AsyncTask enables proper and easy use of the UI thread. This class allows to perform
            background operations and publish results on the UI thread without having
            to manipulate threads and/or handlers.
    */
    private class CheckInternetConnection extends AsyncTask<Void,Void,Boolean>{

        protected Boolean doInBackground(Void...params){
            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.
                */
                InetAddress address = InetAddress.getByName("google.com");
                if(address != null)
                {
                    status = true;
                }
            }catch (Exception e)
            {
                e.printStackTrace();
            }
            return status;
        }

        protected void onPostExecute(Boolean result)
        {
            TextView tv = (TextView) findViewById(R.id.tv);
            if(result){
                tv.setTextColor(Color.BLUE);
                tv.setText("Internet connection available.");
            }
            else {
                tv.setTextColor(Color.RED);
                tv.setText("No internet connection.");
            }
        }
    }
}
AndroidManifest.xml (permission)

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


More android examples