Check Internet Connectivity in Android App - JAVA Version

In this tutorial, you will learn how to implement internet connectivity checking in an Android application using Java. You'll delve into the process of querying the device's network connectivity services within the MainActivity.java file. This involves checking the availability of an active internet connection by using connectivity managers and broadcast receivers, ensuring your app can gracefully handle scenarios where the device might not have internet access. This tutorial will focus on practical implementation steps in Java, enabling robust internet connectivity detection for your Android app.
Submitted on July 07, 2024

To check if internet connectivity is available in an Android app using Java, you typically need to query the system's network connectivity services. Here's how we can implement this in your ‘MainActivity.java’:

Step-by-Step Implementation

1. Update Manifest Permissions

Make sure we have the necessary permissions declared in your ‘AndroidManifest.xml’ file:

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

2. Implement Check Connectivity Method

Add the following method to our ‘MainActivity.java’:


import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        // Check internet connectivity
        if (isInternetAvailable()) {
            Toast.makeText(this, "Internet is available", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Internet is not available", Toast.LENGTH_SHORT).show();
        }
    }

    // Method to check internet connectivity
    private boolean isInternetAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.isConnected();
        }
        return false;
    }
}

      

Explanation:

  • Permissions: Ensure that you have declared the ACCESS_NETWORK_STATE permission in your AndroidManifest.xml file. This permission allows your app to access information about networks.

  • MainActivity (MainActivity.java):

    • In onCreate(), the isInternetAvailable() method is called to check if internet connectivity is present.
  • isInternetAvailable() method:

    • Uses ConnectivityManager to get information about the active network.
    • Checks if there is an active network connection (networkInfo != null && networkInfo.isConnected()).
  • Toast Messages: Depending on the result of isInternetAvailable(), a toast message is displayed indicating whether internet connectivity is available or not.

Additional Notes:

  • Handling Network Changes: Consider registering a BroadcastReceiver to listen for network connectivity changes if your app needs to dynamically respond to changes in connectivity.

  • UI/UX: Instead of Toast, you might want to implement a more user-friendly way to notify users about internet connectivity status, such as using a Snackbar or updating UI elements dynamically.

This implementation should effectively check whether the device has internet connectivity available at the time your activity is created. Adjustments can be made based on your specific application requirements and desired user experience.


Check Internet Connectivity in Android App - Kotlin Version

In this tutorial, you will learn how to implement internet connectivity checking in an Android application using Kotlin. You'll explore the process of implementing a function to check for internet connectivity within your Kotlin-based MainActivity.kt or another Kotlin class. This involves leveraging Kotlin's syntax and Android's connectivity managers to determine if the device has an active internet connection. The tutorial will guide you through practical steps to ensure your app can effectively handle scenarios where internet access may not be available.
Submitted on July 07, 2024

To check if internet connectivity is available in an Android app using Kotlin, you'll follow a similar approach as in Java. Here's how you can implement it:

Implement Check Connectivity Function

Add the following function to your ‘MainActivity.kt’ or any Kotlin class where you want to check internet connectivity:


import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Check internet connectivity
        if (isInternetAvailable()) {
            Toast.makeText(this, "Internet is available", Toast.LENGTH_SHORT).show()
        } else {
            Toast.makeText(this, "Internet is not available", Toast.LENGTH_SHORT).show()
        }
    }

    // Function to check internet connectivity
    private fun isInternetAvailable(): Boolean {
        val connectivityManager =
            getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork
            val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
            return networkCapabilities != null &&
                    (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
                            networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                            networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
        } else {
            val networkInfo = connectivityManager.activeNetworkInfo
            return networkInfo != null && networkInfo.isConnected
        }
    }
}