Monday, December 9, 2013

How to detect network connection in Android

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="http://schemas.android.com/apk/res/android"
    package="com.checknetwork"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
<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.checknetwork.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>

Java Code

Let’s now see the java code for this:

MainActivity.java

package com.checknetwork;
 
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         
        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:
check_network

Download code for this example

0 comments:

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