Android Check Wi-Fi Internet Connection

In this post, we are going to discuss about how to check whether Wi-Fi internet access is active or not in a device. We will develop a simple Android application which will show the status of Wi-Fi internet connectivity.

Before we start with developing application, download code from here to follow with the below listings.

Quick Links

  1. Project Structure
  2. Code Listings
  3. Demo
  4. Download Source Code

Project Structure

Layout creation:

  • Create new android project [File >> New >> Android Project] with project name CheckMobileInternet
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.checkwifiinternet’
  • Click finish

Code Listings

Layout XML:

Open main.xml present under /res/layout folder and replace the XML with the below one.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btn_check"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="Check WiFi Internet Status"
        android:layout_centerInParent="true"/>

</RelativeLayout>

CheckWIFIInternetConn.java

Add below code in CheckWIFIInternetConn.java, is an Activity class which check the internet status and display it in a dialog box on click of a button:

package com.prgguru.checkwifiinternet;

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 CheckWIFIInternetConn extends Activity {

	//Internet status flag
	Boolean isConnectionExist = false;

	// Connection detector class
	WIFIInternetConnectionDetector cd;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button btnStatus = (Button) findViewById(R.id.btn_check);

		// creating connection detector class instance
		cd = new WIFIInternetConnectionDetector(getApplicationContext());

		//Button click listener to check internet status
		btnStatus.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				// get Internet status
				isConnectionExist = cd.checkMobileInternetConn();

				// check for Internet status
				if (isConnectionExist) {
					// Internet Connection exists
					showAlertDialog(CheckWIFIInternetConn.this, "Internet Connection",
							"Your device has WIFI internet access", true);
				} else {
					// Internet connection doesn't exist
					showAlertDialog(CheckWIFIInternetConn.this, "No Internet Connection",
							"Your device doesn't have WIFI internet access", false);
				}
			}

		});

	}

	/**
	 * Function to display simple Alert Dialog
	 * @param context - application context
	 * @param title - alert dialog title
	 * @param message - alert message
	 * @param status - success/failure (used to set icon)
	 * */
	public void showAlertDialog(Context context, String title, String message, Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}
}

I believe below code is self understandable since each line is with added comment.

WIFIInternetConnectionDetector.java

Create a new class ‘WIFIInternetConnectionDetector’ – which will perform the internet connectivity check. Add below code in the class created:

package com.prgguru.checkmobileinternet;

package com.prgguru.checkwifiinternet;

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

public class WIFIInternetConnectionDetector {

	private Context _context;

	public WIFIInternetConnectionDetector(Context context) {
		this._context = context;
	}

	public boolean checkMobileInternetConn() {
		//Create object for ConnectivityManager class which returns network related info
		ConnectivityManager connectivity = (ConnectivityManager) _context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		//If connectivity object is not null
		if (connectivity != null) {
			//Get network info - WIFI internet access
			NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

			if (info != null) {
				//Look for whether device is currently connected to WIFI network
				if (info.isConnected()) {
					return true;
				}
			}
		}
		return false;
	}
}

Add Network permission in Androidmanifest.xml:

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

We are done with the coding part, let us test the application.

[pgsubscribe]

[pglinkadssmall1]

Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

I hope you enjoyed the post!! 🙂
[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • Ram

    Thanks for the tutorial

  • Đỗ Việt Dũng

    Does your code increase performance by split checkMobileInternetConn() to other class? Thanks

    • Just to separate the Internet checking functionality from Activity class, I put it in other class. It is always good practice to have separate class for handling stuffs other than UI.

      • Đỗ Việt Dũng

        okey I got it. Thanks you, let post more example 🙂

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares