Check internet connection in ANDROID


             If you are using internet connection in your android application, then it is important to check the internet connectivity before doing any other operations.
It is simple to check the internet connectivity status in android. ConnectivityManager class given by android sdk gives you ability to :
  1. Monitor network connections (Wi-Fi, GPRS, UMTS, etc.). 
  2. Provides an API that allows applications to query the state of the available networks.
Using which we can easily check Android internet connectivity status.

WI-FI Network details :       
NetworkInfo wifiNetwork = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Above statement will give you wi-fi network details

Mobile Network details :
NetworkInfo mobileNetwork = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
Above statement will give you  mobile network details.

NetworkInfo activeNetwork = connectivityManager .getActiveNetworkInfo();
Above statement can also be used to get an instance that represents the current network connection.

isConnected() method of NetworkInfo class will tell you whether the connection is currently available or not. if(networkInfoInstance.isConnected()){
          //Connection available
}else{
          //Connection unavailable
}

I have created an application to check the internet connectivity status and to display the connection information like Status, Type of the connection, Sub type of the connection, Roaming status (for mobile network).
 This is the project structure;
Project Explorer

Android Manifest permission details :
             We need to add these two permissions to access the connectivity details;
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

My AndroidManifest.xml is given below;


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.internetconnection"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.internetconnection.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>

</manifest>

I am using table layout to display the connectivity details; This is my activity_main.xml layout file;

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <!-- 2 columns -->

    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip" >

        <TextView
            android:id="@+id/textView1"
            android:text="@string/status"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button android:id="@+id/status" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:visibility="gone" >

        <TextView
            android:id="@+id/textView2"
            android:text="@string/type"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button android:id="@+id/type" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:visibility="gone" >

        <TextView
            android:id="@+id/textView3"
            android:text="@string/subtype"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button android:id="@+id/subtype" />
    </TableRow>

    <TableRow
        android:id="@+id/tableRow4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="5dip"
        android:visibility="gone" >

        <TextView
            android:id="@+id/textView4"
            android:text="@string/roaming"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button android:id="@+id/roaming" />
    </TableRow>

</TableLayout>

The string values used in this layout are defined in string.xml file

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

    <string name="app_name">InternetConnection</string>
    <string name="status">Status</string>
    <string name="type">Type</string>
    <string name="subtype">Subtype</string>
    <string name="roaming">Roaming status</string>
    <string name="menu_settings">Settings</string>

</resources>

In my MainActivity.java I have created a method called getConnectionDetails() in which I am checking the connectivity status and other details. If no connection is available, then "Connection unavailable" message will be displayed. Otherwise the connection status and other details will be displayed.

My MainActivity.java is given below

package com.example.internetconnection;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;

/**
 * @author Prabu
 * Check Internet connectivity status and get the details if available.
 */
public class MainActivity extends Activity {

 /**
  * @see android.app.Activity#onCreate(android.os.Bundle)
  */
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  Map<String, String> networkDetails = getConnectionDetails();
  if (networkDetails.isEmpty()) {
   findViewById(R.id.tableRow1).setVisibility(0);
   TextView value = (TextView) findViewById(R.id.status);
   value.setText("Connection unavailable");
  } else {
   if (networkDetails.containsKey("State")) {
    findViewById(R.id.tableRow1).setVisibility(0);
    TextView value = (TextView) findViewById(R.id.status);
    value.setText(networkDetails.get("State"));
   }
   if (networkDetails.containsKey("Type")) {
    findViewById(R.id.tableRow2).setVisibility(0);
    TextView value = (TextView) findViewById(R.id.type);
    value.setText(networkDetails.get("Type"));
   }
   if (networkDetails.containsKey("Sub type")) {
    findViewById(R.id.tableRow3).setVisibility(0);
    TextView value = (TextView) findViewById(R.id.subtype);
    value.setText(networkDetails.get("Sub type"));
   }
   if (networkDetails.containsKey("Roming")) {
    findViewById(R.id.tableRow4).setVisibility(0);
    TextView value = (TextView) findViewById(R.id.roaming);
    value.setText(networkDetails.get("Roming"));
   }
  }
 }

 /**
  * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
  */
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

 /**
  * Get all connection details 1. Status 2. Type: Mobile/wifi 3. Sub type 4.
  * Roaming status (Only for mobile network)
  * 
  * @return Map<String, String>
  */
 private Map<String, String> getConnectionDetails() {
  Map<String, String> networkDetails = new HashMap<String, String>();
  try {
   ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo wifiNetwork = connectivityManager
     .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
   if (wifiNetwork != null && wifiNetwork.isConnected()) {

    networkDetails.put("Type", wifiNetwork.getTypeName());
    networkDetails.put("Sub type", wifiNetwork.getSubtypeName());
    networkDetails.put("State", wifiNetwork.getState().name());
   }

   NetworkInfo mobileNetwork = connectivityManager
     .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
   if (mobileNetwork != null && mobileNetwork.isConnected()) {
    networkDetails.put("Type", mobileNetwork.getTypeName());
    networkDetails.put("Sub type", mobileNetwork.getSubtypeName());
    networkDetails.put("State", mobileNetwork.getState().name());
    if (mobileNetwork.isRoaming()) {
     networkDetails.put("Roming", "YES");
    } else {
     networkDetails.put("Roming", "NO");
    }
   }
  } catch (Exception e) {
   networkDetails.put("Status", e.getMessage());
  }
  return networkDetails;
 }
}



Thats it, now run the application
 
Output Screenshot

Source code of this application is available here InternetConnection.zip
Download the apk file here InternetConnection.apk

 



Reactions:

5 comments :

  1. apk file to install it on the tablet to test?

    ReplyDelete
    Replies
    1. Hi,
      We have uploaded the apk file.

      Delete
  2. i downloaded apk file and imported into eclipse but then i find many errors...can u pls help me resolve it

    ReplyDelete
    Replies
    1. cannot combine swipe dismissal and the action bar... error is getting

      Delete