Showing posts with label Android Network Connection. Show all posts
Showing posts with label Android Network Connection. Show all posts

Sunday, 26 July 2015

Android Check Network Connection

You may be building an application which requires an Internet connection. It is very important to detect the internet connection before the application starts working so that to prevent the application from raising exceptions. Here I am explaining how to achieve the goal.

First you need to include the permissions in the Manifest file after the <application> tag.

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


After including the permissions, just add a few lines of code where you want to detect the internet connection.

ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] arrar_ni = cm.getAllNetworkInfo();
        for (NetworkInfo ni : arrar_ni)
        {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "WiFi Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "WiFi Not Available", Toast.LENGTH_LONG).show();
                }
            }
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            {
                if (ni.isConnected())
                {
                    Toast.makeText(this, "Mobile Available", Toast.LENGTH_LONG).show();
                } else
                {
                    Toast.makeText(this, "Mobile Not Available", Toast.LENGTH_LONG).show();
                }
            }
        }



The above code will generate Toast displaying the availability and type of internet connection. You can replace the Toast statements with your code according to the requirement of your application.