Check Internet Connection Continuously in Android Studio (2023)

Hello Developer, If you want to check the Internet Connection in your app, and you are finding the correct way to implement the internet connection functionality in your app in Android Studio using with Kotlin, so this post for you . In this post, we will be discussing how to monitor internet connection in Android using Kotlin and LiveData (step by step).

After implementing that functionality, it will continuously check the internet connection, if there are any changes happen in the internet connection the observer will return the Boolean value as per the network connection state.

I will share the way to monitor the Network Connection Continuously in an Activity or Fragment and we will use Network Callback with a live data observer. So, without further delay, let’s see: Step-By-Step.

How to Check Internet Connection in Android Studio with Kotlin

Step 1: First, create a new project

  • Open Android Studio.
  • Create a new project.
  • Filling in the project details.
  • Click on finish, now your project is successfully created.

Step 2: Add Permission

Now open Android Manifest, and add the most 2 important permission.

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

Step 3: Create a new XML layout

Create a new XML layout for showing network errors, when you go offline.

  • Go to res
  • layout
  • Right click on layout and select new then select Layout Resource File
  • Give name as network_error.xml and click ok.

Now open the network_error.xml file and write the below code.

<?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"
    android:background="@color/light_purple"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/errorImageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_network_error"
        tools:ignore="ContentDescription" />

    <TextView
        android:id="@+id/errorTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/network_error"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorImageView" />

    <TextView
        android:id="@+id/errormsgTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/internet_check"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: include network error layout

After creating the network error layout and include the network error layout to activity_main.

Open activitiy_main.xml and write the following code in the activity_main.xml

<include
    android:id="@+id/networkError"
    android:visibility="gone"
    layout="@layout/network_error"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Now design part is completed, let’s move to check the internet connection continuously

Step 5: Create a new Kotlin Class

Create a new Kotlin Class name as NetworkConnection.

package com.techpassmaster.androidcheckinternetconnection

class NetworkConnection(){
}

Step 6: Pass a context as a parameter

Now pass a context as a parameter and extend the class with LiveData()

class NetworkConnection(private val context: Context) : LiveData() {

}

Step 7: Create connectivityManager

Create connectivityManager which will be extending ConnectivityManager and it is responsible for Monitor network connection, Attempt to fail network when connectivity to a network is lost and etc and also you have to create a networkConnectionCallback variable for NetworkCallback in which you have to get two callbacks:

  • onLost
  • onAvailable
class NetworkConnection(private val context: Context) : LiveData() {

private val connectivityManager: ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
private lateinit var networkConnectionCallback: ConnectivityManager.NetworkCallback

}

Step 8: Create connectivityManagerCallback

Create connectivityManagerCallback function for post the false value, when the connection is lost, and post true value when the internet is available. write the below code.

private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {    
networkConnectionCallback = object : ConnectivityManager.NetworkCallback() {

        override fun onLost(network: Network) {
            super.onLost(network)
            postValue(false)
        }

        override fun onAvailable(network: Network) {
            super.onAvailable(network)
            postValue(true)
        }
    }
    return networkConnectionCallback
}
}

Step 9: Create updateNetworkConnection

Now create the updateNetworkConnection function which is used to post the true value and the internet is connected and also creates a variable that overrides the OnRecive function and it is responsible to update Network Connection.

private fun updateNetworkConnection() {
        val activeNetworkConnection: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetworkConnection?.isConnected == true)
}

private val networkReceiver= object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            updateNetworkConnection()
        }
}

Step 10: Override two function

So this is the last step, just you have to override two functions.

  • onActive
  • onInactive

Write the below code.

override fun onActive() {
super.onActive()    
updateNetworkConnection()
    when {
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
            connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
        }
        else -> {
            context.registerReceiver(
                networkReceiver,
                IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            )
        }
    }
}

override fun onInactive() {
    super.onInactive()
    connectivityManager.unregisterNetworkCallback(connectivityManagerCallback())
}

Final NetworkConnection code for Check Internet Connection Continuously

So the final code for continuously checking network connection would be.

  • network_error.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"
    android:background="@color/light_purple"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/errorImageView"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/ic_network_error"
        tools:ignore="ContentDescription" />

    <TextView
        android:id="@+id/errorTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/network_error"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorImageView" />

    <TextView
        android:id="@+id/errormsgTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:gravity="center"
        android:text="@string/internet_check"
        android:textColor="@color/white"
        app:layout_constraintTop_toBottomOf="@+id/errorTextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:gravity="center"
    android:orientation="vertical">

    <include
        android:id="@+id/networkError"
        android:visibility="gone"
        layout="@layout/network_error"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
  • NetworkConnection.kt
@file:Suppress("DEPRECATION")

package com.techpassmaster.androidcheckinternetconnection

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkInfo
import android.os.Build
import androidx.lifecycle.LiveData

@Suppress("DEPRECATION")
class NetworkConnection(private val context: Context) : LiveData<Boolean>() {

    private val connectivityManager: ConnectivityManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

    private lateinit var networkConnectionCallback: ConnectivityManager.NetworkCallback

    override fun onActive() {
        super.onActive()

        updateNetworkConnection()
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> {
                connectivityManager.registerDefaultNetworkCallback(connectivityManagerCallback())
            }
            else -> {
                context.registerReceiver(
                    networkReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
                )
            }
        }
    }

    override fun onInactive() {
        super.onInactive()
        connectivityManager.unregisterNetworkCallback(connectivityManagerCallback())
    }

    private fun connectivityManagerCallback(): ConnectivityManager.NetworkCallback {

        networkConnectionCallback = object : ConnectivityManager.NetworkCallback() {

            override fun onLost(network: Network) {
                super.onLost(network)
                postValue(false)
            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                postValue(true)
            }
        }
        return networkConnectionCallback
    }

    private fun updateNetworkConnection() {
        val activeNetworkConnection: NetworkInfo? = connectivityManager.activeNetworkInfo
        postValue(activeNetworkConnection?.isConnected == true)
    }

    private val networkReceiver= object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            updateNetworkConnection()
        }
    }
}

Now call the Network connection observer in the Activity or Fragment for checking internet is connected or not.

  • Open Main Activity and write the below code.
package com.techpassmaster.androidcheckinternetconnection

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.transition.Visibility

class MainActivity : AppCompatActivity() {


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

        val layoutInflater = findViewById<View>(R.id.networkError)

        val networkConnection= NetworkConnection(applicationContext)

        networkConnection.observe(this) { isConnected ->

            if (isConnected) {
                Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show()
                layoutInflater.visibility= View.GONE
            } else {
                Toast.makeText(this, "Not Connected", Toast.LENGTH_SHORT).show()
                layoutInflater.visibility= View.VISIBLE
            }
        }
    }
}
Read More 
I hope you liked the post. If you have any questions regarding this post. Feel free to comment and share the post with other developers.

Happy Learning!!!  :)

Leave a Reply

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