How to Check Internet Connection in Kotlin?

28 Jul, 2021
If the Android application is developing, which is internet-based, then there must be a feature that checks for internet connectivity and informs the user there is no internet available. So in this article, it’s been demonstrated step by step. On how to check the internet connectivity. Have a look at the following image which gives an overview of the discussion.
Step 1: Create an empty activity project
Create an empty activity android studio project. Refer to How to Create/Start a New Project in Android Studio, to know how to create an empty activity project. And select Kotlin as the programming language.
Step 2: Working with acitivity_main.xml file
The main layout of the application contains only one button. Which upon clicking, a toast appears which contains the status of the connectivity.
To implement the same UI invoke the following code inside the acitivity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">      <Button        android:id="@+id/buttonCheck"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="CHECK FOR CONNECTION"        android:textColor="@color/white"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout>
Output UI:
Step 3: Working with MainActivity.kt file
The MainActivity.kt file contains some already built-in API which used to handle the network connectivity.
First, we should register the activity with the ConnectivityManager service.
Second, we need to check for the android version. if the version is below M uses activeNetworkInfo API, or if the version is equal to or above M use NetworkCapabilities API.
To implement the same invoke the following code inside the MainActivity.kt file comments are added for better understanding.
Kotlin
import android.content.Contextimport android.net.ConnectivityManagerimport android.net.NetworkCapabilitiesimport android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast  class MainActivity : AppCompatActivity() {      override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)          // register the UI element button        val checkButton: Button = findViewById(R.id.buttonCheck)          // handle the button click to trigger        // checkForInternet function        // and show the Toast message according to it.        checkButton.setOnClickListener {            if (checkForInternet(this)) {                Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show()            } else {                Toast.makeText(this, "Disconnected", Toast.LENGTH_SHORT).show()            }        }    }      private fun checkForInternet(context: Context): Boolean {          // register activity with the connectivity manager service        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager          // if the android version is equal to M        // or greater we need to use the        // NetworkCapabilities to check what type of        // network has the internet connection        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {              // Returns a Network object corresponding to             // the currently active default data network.            val network = connectivityManager.activeNetwork ?: return false                        // Representation of the capabilities of an active network.            val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false              return when {                // Indicates this network uses a Wi-Fi transport,                // or WiFi has network connectivity                activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true                                // Indicates this network uses a Cellular transport. or                 // Cellular has network connectivity                activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true                  // else return false                else -> false            }        } else {            // if the android version is below M            @Suppress("DEPRECATION") val networkInfo =                connectivityManager.activeNetworkInfo ?: return false            @Suppress("DEPRECATION")            return networkInfo.isConnected        }    }}
Output:
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.