Android Detect Internet Connection Status [UPDATED]

In android, by using ConnectivityManager class we can easily determine whether the network or internet connected or not and also we can determine the type of internet connection currently available i.e. whether it’s mobile data or Wi-Fi.

To get the internet connection status, our app must acquire the INERTNET and ACCESS_NETWORK_STATE permissions. For that, we need to add the following permissions in android manifest file like as shown below.

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

Check Internet Connection Status

In android, we can determine the internet connection status easily by using getActiveNetworkInfo() method of ConnectivityManager object.

Following is the code snippet of using ConnectivityManager class to know whether internet connection available or not.

ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
boolean connected = nInfo != null && nInfo.isAvailable() && nInfo.isConnected();


If you observe above code snippet, we used getActiveNetworkInfo() method of ConnectivityManager object to know whether internet connection available or not.

Determine the Type of Internet Connection

In android, we can easily determine the type of internet connection currently available i.e. either WI-FI or mobile data by using getType() method of NetworkInfo object.

Following is the code snippet to get the type of internet connection in android application.

ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
boolean isWiFi = nInfo.getType() == ConnectivityManager.TYPE_WIFI;



If you observe above code snippet, we used getType() method of NetworkInfo object to know the type of internet connection.

Now we will see how to save files directly on the device’s internal memory and read the data files from device internal memory by using FileOutputStream and FileInputStream objects in android application with examples.

Android Internet Connection Example

Following is the example of checking whether the internet connection available or not using android ConnectivityManager object.

Create a new android application using android studio and give names as InternalConnectionExample.

Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <
Button
        android:id="@+id/btnCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:text="Check Internet Connection" />
</
LinearLayout>
 
Now open your main activity file MainActivity.java  and write the code like as shown below

MainActivity.java


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
   
@Override
    protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
        Button btnStatus = (Button)findViewById(R.id.
btnCheck);
        btnStatus.setOnClickListener(
new View.OnClickListener() {
           
@Override
            public void onClick(View v) {
              
// Check for Internet Connection
                if (isConnected()) {
                    Toast.makeText(getApplicationContext(),
"Internet Connected", Toast.LENGTH_SHORT).show();
                }
else {
                    Toast.makeText(getApplicationContext(),
"No Internet Connection", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
   
public boolean isConnected() {
       
boolean connected = false;
       
try {
            ConnectivityManager cm = (ConnectivityManager)getApplicationContext().getSystemService(Context.
CONNECTIVITY_SERVICE);
            NetworkInfo nInfo = cm.getActiveNetworkInfo();
            connected = nInfo !=
null && nInfo.isAvailable() && nInfo.isConnected();
           
return connected;
        }
catch (Exception e) {
            Log.e(
"Connectivity Exception", e.getMessage());
        }
       
return connected;
    }
}
 
 
If you observe above code, we are getting the internet connection status by using ConnectivityManager object.

Now we need to acquire the permissions of INTERNET and ACCESS_NETWORK_STATE for our android application for that open AndroidManifest.xml file and add the permissions like as shown below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androtutts.internetconnectionexample">
    <
uses-permission android:name="android.permission.INTERNET"/>
    <
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <
application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />
                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>
</
manifest>
 
If you observe above example, we are getting the internet connection status and added required permissions in AndroidManifest.xml file.

Output of Android Internet Connection Example

When we run above example in android emulator we will get a result like as shown below.


  1. Enable your Wifi/Data
Network Connected
2. Disable your Wifi/Data
Network Not Connected



If you observe above result, When we click on Check Internet Connection button it will fetch the status of internet connection whether the internet available not.

This is how we can check the internet connection status in android applications using ConnectivityManager object based on our requirements.

Comments

Popular posts from this blog

20+ Awesome Open-Source Android Apps To Boost Your Development Skills [ 2019 ]

Android MaterialDrawer - A Custom Navigation Drawer

Android-How To Reload Fragment & Activities