This sample code checks whether the android device is connected to Internet and
if it is connected to internet, it is connected to Wifi or Not?

package com.coderzheaven.demo1;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

public class MainActivity extends Activity {

	NetworkInfo activeNetwork;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (connectedToInternet())
			System.out.println("Connected to Internet.");
		else
			System.out.println("Not Connected to internet");

		if (isWifi())
			System.out.println("Connected to Wifi.");
		else
			System.out.println("Not Connected to Wifi");
	}

	Boolean connectedToInternet() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		activeNetwork = cm.getActiveNetworkInfo();
		return (activeNetwork != null && activeNetwork
				.isConnectedOrConnecting());

	}

	Boolean isWifi() {
		return (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI);
	}
}

MAKE SURE YOU ADD BELOW PERMISSION TO THE ANDROID MANIFEST

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

2 Comments

  1. abcdef November 6, 2014 at 8:27 am

    Well, no! Being connected to WiFi does not mean that you’re connected to Internet. Think about a situation you’re connected to wifi router with no uplink connection at all: Your code would happily claim you’re connected to Internet in that case.

     
    • James November 6, 2014 at 11:03 am

      Yes, you are right, you have to check for the response code in that case.
      if responsecode == 200 connected.
      I just demonstrated a way to check if device is connected or not.

      Thanks for the comment.

       

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.