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 CheckInternetConnection.java 

Open your CheckInternetConnection.java and paste the following code.

CheckInternetConnection.java

package com.androidbegin.checkinternetconnection;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
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;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.check_internet_connection);
		// 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")
					.setCancelable(false)
					.setPositiveButton("Retry",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// Restart the Activity
									Intent intent = getIntent();
									finish();
									startActivity(intent);
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
		} else {
			// Locate the button in check_internet_connection.xml
			visitbtn = (Button) findViewById(R.id.visit);
			// Set the button visibility
			visitbtn.setVisibility(View.VISIBLE);
			// Capture Button click
			visitbtn.setOnClickListener(new OnClickListener() {

				public void onClick(View arg0) {
					// Recheck Network Connection
					if (!isNetworkAvailable()) {
						AlertDialog.Builder builder = new AlertDialog.Builder(
								CheckInternetConnection.this);
						builder.setMessage("Internet Connection Required")
								.setCancelable(false)
								.setPositiveButton("Retry",
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												visitbtn.setVisibility(View.GONE);
												// Restart the activity
												Intent intent = new Intent(
														CheckInternetConnection.this,
														CheckInternetConnection.class);
												finish();
												startActivity(intent);

											}

										});
						AlertDialog alert = builder.create();
						alert.show();

					} else {
						// Open Android Browser
						Intent intent = new Intent(Intent.ACTION_VIEW, Uri
								.parse("http://www.AndroidBegin.com"));
						startActivity(intent);
					}

				}
			});
		}
	}

	// Private class isNetworkAvailable
	private boolean isNetworkAvailable() {
		// Using ConnectivityManager to check for Network Connection
		ConnectivityManager connectivityManager = (ConnectivityManager) this
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		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.

check_internet_connection.xml

<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" >

    <Button
        android:id="@+id/visit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/visit"
        android:visibility="gone" />

</RelativeLayout>

Output:

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

strings.xml

<resources>

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

</resources>

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.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.checkinternetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity android:name=".CheckInternetConnection" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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.show(); 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("http://www.jaiganeshoctroi.com/shivmudra/shivmudra.txt"); 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(R.id.listview); // Pass the results into ListViewAdapter.java 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.

AndroidBegin

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