Monday, December 9, 2013

By using the connectivity service, we can check if the device is hooked to the network or not. If network connection is present then we can detect if it is of type Wifi or mobile data.

Android Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    android:versionName="1.0" >
        android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Java Code

Let’s now see the java code for this:

package com.checknetwork;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        ConnectivityManager cmanager = (ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
        NetworkInfo info = cmanager.getActiveNetworkInfo();
        if(info!=null && info.isConnected()) {
            if(info.getType() == ConnectivityManager.TYPE_WIFI) {
                Toast.makeText(MainActivity.this, "Wifi", Toast.LENGTH_LONG).show();   
            } else if(info.getType() == ConnectivityManager.TYPE_MOBILE) {
                Toast.makeText(MainActivity.this, "mobile", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(MainActivity.this, "Not connected", Toast.LENGTH_LONG).show();

Screenshots for checking network connection in Android

1) As soon as app is launched, network status is shown as a toast message:

Download code for this example

Copyright © 2012 Making Money With Android| Design by Blogspot Templates.