Check Internet Connectivity in Android

Introduction

This article explains how to check an internet connection in Android. Android Studio is used to create the sample. For this, first in your XML file you will use a button and on its click you will check an internet connection.
In your Java file you will create the id of a button and set it on its click event. Inside the button click you will determine whether the internet connection is present that will be returned by the ConnectingInternet() method. If it returns true then an alert dialogue is shown that contains the text "Internet connected" otherwise the internet is not connected.

In the "ConnectiingInternet()" method you will get the object of the Connectivity manager class by calling "getSystemSerivces()". After getting the object you will determine whether the connectivity is not null then get all the information about the network by calling the "getAllnetworkInfo()" method. Determine whether the about info is not equal to null and if it is not equal to null then it returns true otherwise false.

Step 1

Create a project like this:

checkinternet3

Step 2

Create an XML file and write the following.

 In your XML file you will use a button and on its click you will check for an internet connection.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:paddingBottom="@dimen/activity_vertical_margin"

    tools:context=".MainActivity"

    android:background="#000000">

 

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="checkInternet"

        android:textStyle="bold"

        android:textSize="30dp"

        android:layout_centerHorizontal="true"/>

 

    <Button

        android:id="@+id/check_button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

 

        android:text="checkInternet" />

 

 

 

</RelativeLayout>


Step 3
 

Create a Java file with the following code.

In your Java file you will create the id of a button and set it on its click event. Inside the button click you will determine whether an internet connection is present that will be returned by the ConnectingInternet() method. If it returns true then an alert dialogue is shown that contains the text "Internet connected" otherwise the internet is not connected.

In the "ConnectiingInternet()" method you will get the object of the Connectivity Manager class by calling "getSystemSerivces()". After getting the object you will determine whether the connectivity is not null then get all the information about the network by calling the "getAllnetworkInfo()" method. Check the about info to determine whether it is not equal to null; if it is not equal to null then it returns true otherwise false.

package com.projectinternet;

 

import android.app.Activity;

import android.app.AlertDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

 

public class MainActivity extends Activity {

    Boolean InternetAvailable = false;

    Button checkInternet;

    Seocnd detectconnection;

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        checkInternet = (Button) findViewById(R.id.check_button);

        detectconnection = new Seocnd(getApplicationContext());

        checkInternet.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                InternetAvailable = detectconnection.InternetConnecting();

                if (InternetAvailable) {

                    showAlertDialog(MainActivity.this, "Internet Connection",

                            "internet is available", true);

                } else {

                    showAlertDialog(MainActivity.this, "No Internet Connection",

                            "internet is not available", false);

                }

            }

        });

    }

    public void showAlertDialog(Context context, String t, String m, Boolean status) {

        AlertDialog message = new AlertDialog.Builder(context).create();

        message.setTitle(t);

        message.setMessage(m);

       // message.setIcon((status) ? R.drawable.success : R.drawable.fail);

        message.setButton("OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

            }

        });

        message.show();

    }

}

 

Step 4

Create another Java file and write this:

package com.projectinternet;

import android.content.Context;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

 

public class Seocnd {

    private Context context;

    public Seocnd(Context c){

        this.context = c;

    }

    public boolean InternetConnecting(){

        ConnectivityManager connect = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connect != null)

        {

            NetworkInfo[] information = connect.getAllNetworkInfo();

            if (information != null)

                for (int x = 0; x < information.length; x++)

                    if (information[x].getState() == NetworkInfo.State.CONNECTED)

                    {

                        return true;

                    }

        }

        return false;

    }

}

Step 5

Add internet permission in the Android "Menifest.xml" file as in the following:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.projectinternet"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="7"

        android:targetSdkVersion="16" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.projectinternet.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

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

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

 

</manifest>


Step 6

Check the internet connection as in the following:

checkinternet

checkinternet2

Up Next
    Ebook Download
    View all
    Learn
    View all