Android Check Mobile Internet Connection

In this post, we are going to discuss about how to check whether mobile internet access is active or not in a device. We will develop a simple Android application which will show the status of mobile 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.checkmobileinternet’
  • 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 Mobile Internet Status"
        android:layout_centerInParent="true"/>

</RelativeLayout>

CheckMobileInternet.java

[pgsubscribe]

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

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

package com.prgguru.checkmobileinternet;

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

	//Internet status flag
	Boolean isConnectionExist = false;

	// Connection detector class
	MobileInternetConnectionDetector 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 MobileInternetConnectionDetector(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(CheckMobileInternet.this, "Internet Connection",
							"Your device has mobile internet", true);
				} else {
					// Internet connection doesn't exist
					showAlertDialog(CheckMobileInternet.this, "No Internet Connection",
							"Your device doesn't have mobile internet", 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();
	}
}

MobileInternetConnectionDetector.java

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

package com.prgguru.checkmobileinternet;

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

public class MobileInternetConnectionDetector {

	private Context _context;

	public MobileInternetConnectionDetector(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 - Mobile internet access
			NetworkInfo info = connectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

			if (info != null) {
				//Look for whether device is currently connected to Mobile internet
				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.

[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
  • Soufian

    I’m using this one, and it’s working perfect:

    public boolean isConnected() {
    ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfo info = manager.getActiveNetworkInfo();
    if (info != null && info.isConnected()) {
    return true;
    } else {
    return false;

    }
    }

    Github:

    https://gist.github.com/78f00ad97f1b4eb7af2c

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