Android Check Internet Connection

In this tutorial, you will learn how to check Internet connectivity status before running your Android application. Using Android ConnectivityManager allows the user to detect network connection status. We will create an application that will perform two level Internet connection status checking. First level checks for Internet Connection status when the application launches and the second level checks when the user click on a button. If the Internet connection does not exist, a dialog box with a retry button will be shown and on the retry button click will recheck the Internet connection status.

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project CheckInternetConnection.

Application Name : CheckInternetConnection

Project Name : CheckInternetConnection

Package Name : com.androidbegin.checkinternetconnection

Then name your activity 

Open your and paste the following code.

package com.androidbegin.checkinternetconnection;

import android.os.Bundle;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CheckInternetConnection extends Activity {

	// Declare a button
	Button visitbtn;

	public void onCreate(Bundle savedInstanceState) {
		// Call isNetworkAvailable class
		if (!isNetworkAvailable()) {
			// Create an Alert Dialog
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			// Set the Alert Dialog Message
			builder.setMessage("Internet Connection Required")
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// Restart the Activity
									Intent intent = getIntent();
			AlertDialog alert = builder.create();;
		} else {
			// Locate the button in check_internet_connection.xml
			visitbtn = (Button) findViewById(;
			// Set the button visibility
			// Capture Button click
			visitbtn.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					// Recheck Network Connection
					if (!isNetworkAvailable()) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
						builder.setMessage("Internet Connection Required")
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												// Restart the activity
												Intent intent = new Intent(


						AlertDialog alert = builder.create();;

					} else {
						// Open Android Browser
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri


	// Private class isNetworkAvailable
	private boolean isNetworkAvailable() {
		// Using ConnectivityManager to check for Network Connection
		ConnectivityManager connectivityManager = (ConnectivityManager) this
		NetworkInfo activeNetworkInfo = connectivityManager
		return activeNetworkInfo != null;


This activity checks for an Internet connection before your Android application launches. We have created a private class “isNetworkAvailable()” that can be called anywhere within your activity to check for Internet Connection status by using ConnectivityManager. If the Internet connection or network connection does not exist, we will show a dialog box to the user to recheck the Internet Connection status.

Next, create an XML file for your Graphical Layout. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file check_internet_connection.xml and paste the following code.


<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

        android:visibility="gone" />



CheckInternetConnection XML Main

Next, change the button text in strings.xml. Open your strings.xml and paste the following code. Go to res > values > strings.xml



    <string name="app_name">Check Internet Connection Tutorial</string>
    <string name="menu_settings">Settings</string>
    <string name="visit">Visit</string>


In your AndroidManifest.xml, we need to declare permissions to allow the application to access to the Internet and check on network connection status. Open your AndroidManifest.xml and paste the following code.


<manifest xmlns:android=""
    android:versionName="1.0" >

        android:targetSdkVersion="15" />

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

        android:theme="@style/AppTheme" >
        <activity android:name=".CheckInternetConnection" >
                <action android:name="android.intent.action.MAIN" />

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


Output :

CheckInternetConnection ScreenShots

Source Code 

[purchase_link id=”7846″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Hello SirI Have Following Code How Can I Insert Error Connection Message In My Codepublic class Treking extends Activity { // Declare Variables JSONObject jsonobject; JSONArray jsonarray; ListView listview; ListViewAdapter adapter; ProgressDialog mProgressDialog; ArrayList<HashMap> arraylist; static String RANK = "rank"; static String COUNTRY = "country"; static String POPULATION = "population"; static String DESCRIPTION = "description"; static String FLAG = "flag"; static String FLAGS = "flags"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Get the view from listview_main.xml setContentView(R.layout.listview_main); // Execute DownloadJSON AsyncTask new DownloadJSON().execute(); } // DownloadJSON AsyncTask private class DownloadJSON extends AsyncTask { @Override protected void onPreExecute() { super.onPreExecute(); // Create a progressdialog mProgressDialog = new ProgressDialog(Treking.this); // Set progressdialog title mProgressDialog.setTitle("Connecting server"); // Set progressdialog message mProgressDialog.setMessage("Loading..."); mProgressDialog.setIndeterminate(false); // Show progressdialog; mProgressDialog.setCancelable(true); } @Override protected Void doInBackground(Void... params) { // Create an array arraylist = new ArrayList<HashMap>(); // Retrieve JSON Objects from the given URL address jsonobject = JSONfunctions .getJSONfromURL(""); try { // Locate the array name in JSON jsonarray = jsonobject.getJSONArray("worldpopulation"); for (int i = 0; i < jsonarray.length(); i++) { HashMap map = new HashMap(); jsonobject = jsonarray.getJSONObject(i); // Retrive JSON Objects map.put("rank", jsonobject.getString("rank")); map.put("country", jsonobject.getString("country")); map.put("population", jsonobject.getString("population")); map.put("description", jsonobject.getString("description")); map.put("flag", jsonobject.getString("flag")); map.put("flags", jsonobject.getString("flags")); // Set the JSON Objects into the array arraylist.add(map); } } catch (JSONException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void args) { // Locate the listview in listview_main.xml listview = (ListView) findViewById(; // Pass the results into adapter = new ListViewAdapter(Treking.this, arraylist); // Set the adapter to the ListView listview.setAdapter(adapter); // Close the progressdialog mProgressDialog.dismiss(); } }}

Vinayak Parab

Android Check Internet Connection

then what? kill the thread that uses the internet? it's not a good thing to do. there must be a better way. a timeout could also be nice in case something is wrong with the connection (too slow or the other side isn't responding)...

Android Developer

Android Check Internet Connection

You will need a broadcast receiver to detect any changes with your connection.


Android Check Internet Connection

What if the internet connection was lost during communication? Is there a way to set a timeout for the whole application ?

Android Developer

Android Check Internet Connection